Zach Curtis Zach Curtis - 3 months ago 13
CSS Question

Pause a video with firstChild?

Super new to Javascript, and I'm having trouble finding any solutions to this anywhere. I'm not sure if the issue is with firstChild, or with .pause()

The "tabcontent[i].firstChild.pause()" line breaks the entire function...

Here's a JSFiddle with the effected code, but no image/videos because they are still local.

And here's the effected code here:

HTML:

<div class="video-portfolio">
<div class="video-nav-contain">
<ul class="video-nav">
<li id="hide1">
<a href="#" class="tablinks" onclick="openVideo(event, 'garageBar')">
<img class="tab-icon" src="images/garage-bar-tab.png" onClick="videoDisplay1">
</a>
</li>
<li id="hide2">
<a href="#" class="tablinks" onclick="openVideo(event, 'murryLake')">
<img class="tab-icon" src="images/murry-lake-tab.png">
</a>
</li>
<li id="hide3">
<a href="#" class="tablinks" onclick="openVideo(event, 'roofFun')">
<img class="tab-icon" src="images/roof-fun-tab.png">
</a>
</li>
</ul>
</div>
<div id="garageBar" class="tabcontent" id="videoName">
<video class="vid-tabs" controls>
<source src="images/garage%20bar.mp4" type="video/mp4">
</video>
</div>
<div id="murryLake" class="tabcontent">
<video class="vid-tabs" controls>
<source src="images/murry%20lake2.mp4" type="video/mp4">
</video>
</div>
<div id="roofFun" class="tabcontent">
<video class="vid-tabs" controls>
<source src="images/rooftop%20fun.mp4" type="video/mp4">
</video>
</div>
</div>


And then the Javascript:

function openVideo(evt, videoName) {
var i, tabcontent, tablinks;
tabcontent = document.getElementsByClassName("tabcontent");
for (i = 0; i < tabcontent.length; i++) {
tabcontent[i].style.display = "none";
tabcontent[i].firstChild.pause()
}
tablinks = document.getElementsByClassName("tablinks");
for (i = 0; i < tablinks.length; i++) {
tablinks[i].className = tablinks[i].className.replace(" active", "");
}
document.getElementById(videoName).style.display = "block";
evt.currentTarget.className += " active";
}

Answer

The problem is not with pause() but with firstChild. the video element is coming to be the second child. firstChild gives the output as #text

Use childNodes[1] to access the second child i.e the video

tabcontent[i].childNodes[1].pause();

JS

 <script>
    function openVideo(evt, videoName) {
    var i, tabcontent, tablinks;
    tabcontent = document.getElementsByClassName("tabcontent");
    for (i = 0; i < tabcontent.length; i++) {
        tabcontent[i].style.display = "none";
        console.log(tabcontent[i].childNodes[1]);
    tabcontent[i].childNodes[1].pause();
    }
    tablinks = document.getElementsByClassName("tablinks");
    for (i = 0; i < tablinks.length; i++) {
        tablinks[i].className = tablinks[i].className.replace(" active", "");
    }
    document.getElementById(videoName).style.display = "block";
    evt.currentTarget.className += " active";
}
    </script>

JSFIDDLE

Comments