javascriptjqueryonclickremoveclass

Toggle class using javascript between two


classList to remove class using Javascript is not working, or is it because of any other error in code

Code: http://codepen.io/DPK_RAO/pen/VPXxoJ/

    <ul class="nav">
        <li><a href="#video1" id="link1" class="link1">Video 1</a></li>
        <li><a href="#video2" id="link2" class="link2">Video 2</a></li>
    </ul>

    <div class="video1 active" id="video1">Link 1</div>
    <div class="video2" id="video2">Link 2</div>

CSS:

.video1, .video2{
   display:none;
}

.active{
  display:block;
}

JS

document.getElementById("link1").addEventListner("click", activeVideo1);

function activeVideo1(){
    document.getElementById("video2").classList.remove("active");
    var v1 = document.getElementById("video1");
    v1.className += "active";
}

document.getElementById("link2").addEventListner("click", activeVideo2);

function activeVideo2(){
    document.getElementById("video1").classList.remove("active");
    var v2 = document.getElementById("video2");
    v2.className += "active";
}

Solution

  • When I run the script I get the following error in the console:

    Uncaught TypeError: document.getElementById(...).addEventListner is not a function

    So your script isn't even getting to the removeClass function and it stops in the event's listener part.

    You write the function with a typo. it's

    addEventListener

    Another note:

    Replace this:

    v1.className += "active";
    

    with:

    v1.className += " active"; //added a blank
    

    Updated codepen