javascript - How to change html5 video source on click? -


what i'm trying create sort of playlist, using html5 , vanilla javascript (no jquery). same short video keeps looping until click 1 of arrows, next (or previous) video in line gets loaded in same video element.

here's have:

html

<video autoplay="true" loop="true" id="video">     <source src="img-vid/video1.mp4" type="video/mp4" id="vid-src"> </video> <img src="img-vid/arrow_left.png" class="arrow arrow-left" id="left"> <img src="img-vid/arrow_right.png" class="arrow arrow-right" id="right"> 

javascript

var button_next = document.getelementbyid("right"); var button_previous = document.getelementbyid("left"); var playlist = document.getelementbyid("video"); var source = document.getelementbyid("vid-src");  button_next.onclick = play_next; button_previous.onclick = play_prev;  function play_next() {     var filename = '';     if (source.src == "img-vid/video1.mp4"){         filename = "video2";     }     else if (source.src == "img-vid/video2.mp4"){         filename = "video3";     }     else if (source.src == "img-vid/video3.mp4"){         filename = "video4";     }     else {         filename = "video1";     }     source.src = "img-vid/" + filename + ".mp4";     playlist.load();     playlist.play(); }  //same function play_prev(), order of videos reversed 

however, code, clicking either arrow doesn't seem anything. i'm not sure i'm doing wrong though. first thought if-tests failing, re-loaded same video, after removing tests , setting filename "video2", didn't anything.

edit 1: changed scope on var filename, dev-one suggested. video source still doesn't change though.

edit 2: changing following:

button_next.onclick = play_next; button_previous.onclick = play_prev; 

to

button_next.addeventlistener("click", play_next); button_previous.addeventlistener("click", play_prev); 

seems help. when clicking on arrows now, video changes, not correct one. pressing arrow-right brings video1, while pressing arrow-left shows video3. these videos in last else-statement each method, there still seems issue if-tests.

edit 3: working planned! had change

source.src == ... 

to

source.getattribute("src") == ... 

in if-tests. source.src returned full url (http://..../img-vid/video1.mp4), not relative 1 (img-vid/video1.mp4), every if-test failed.

as mentioned in edits made, managed solve problem changing button.onclick button.addeventlistener() , changing source.src source.getattribute("src").


Comments

Popular posts from this blog

ios - RestKit 0.20 — CoreData: error: Failed to call designated initializer on NSManagedObject class (again) -

java - Digest auth with Spring Security using javaconfig -

laravel - PDOException in Connector.php line 55: SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: YES) -