Search code examples
javascriptcsshtml5-videotoggletogglebutton

JavaScript Toggle with button


So i have a button that what it does it toggles and displays a video. If clicked again it will hide it and on and on. It works fine the only problem is that when the first time you click it you have to click it twice for some reason i can't seem to figure it out.

function togglevid() {
    var e = document.getElementById("movie");
    if (e.style.display == 'none') e.style.display = 'block';
    else e.style.display = 'none';
    if (e.pause == false) e.pause()
    else e.pause()
}
#movie {
    position:absolute;
    top:158px;
    left:470px;
    display:none;
    z-index:10
}
<video controls="" height="400" id="movie" oncontextmenu="return false;"
    width="960">
    <source src="" type="video/mp4">
    Your browser does not support HTML5 video.</video>

<input id="mcodebtn" onclick="togglevid()" type="button" value=
                "">

I believe the reason for this error is the fact i have the video set to display: none; by default.


Solution

  • Try below code, style property should be set to display:none.

    The problem is that you are trying to access style property and then access display value. But the first time you run it, video tag does not have any style attribute set.

    function togglevid() {
        var s = document.getElementById("newcode");
        var e = document.getElementById("movie");
        if (e.style.display == 'none') e.style.display = 'block';
        else e.style.display = 'none';
        if (s.style.display == 'none') s.style.display = 'block';
        else s.style.display = 'none';
        if (e.pause == false) e.pause()
        else e.pause()
    }
    #movie {
        position:absolute;
        top:158px;
        left:470px;
        display:none;
        z-index:10
    }
    <video controls="" 
           height="400" 
           id="movie" 
           oncontextmenu="return false;"
           width="960" 
           style="display:none;"><!-- Here we set a default value for style attr-->
        <source src="" type="video/mp4">
        Your browser does not support HTML5 video.</video>
    
    <input id="mcodebtn" onclick="togglevid()" type="button" value=
                    "">