John Smith John Smith - 3 months ago 11
HTML Question

How to Change ID onClick with javascript and reset the other functions

This is an example of what I am trying to do :

<iframe id="toChange" width="560" height="315" src="https://www.youtube.com/embed/FirstLink" frameborder="0" allowfullscreen></iframe>

<a id="__1__" onclick="changeto1()" > Video 1</a>
<a id="__2__" onclick="changeto2()" > Video 2</a>
<a id="__3__" onclick="changeto3()" > Video 3</a>


<script>
function changeto1(){
document.getElementById('toChange').src='https://www.youtube.com/embed/LINK1';
document.getElementById('__1__').id="active";
}

function changeto2(){
document.getElementById('toChange').src='https://www.youtube.com/embed/LINK2';
document.getElementById('__2__').id="active";
}

function changeto3(){
document.getElementById('toChange').src='https://www.youtube.com/embed/LINK3';
document.getElementById('__3__').id="active";
}
</script>


And it works but, I need to reset the functions after. Because when I click on Video 1 I will get
id="active"
also if I click on Video 2 it get's
id=active
, so they have the same id. :)

I need to reset them, for example if I click on Video 2 its
id="active"
and reset all others... Any other idea will help me.
Thanks.

Answer

As suggested by @yuriy636 you shouldn't change the id value of your <a> tag , instead you should work on their class name value.

<html>

    <head>
        <script>
    function change(id) {
        var src = "";
        switch (id) {
            case 1:
                src = 'https://www.youtube.com/embed/LINK1';
                break;
            case 2:
                src = 'https://www.youtube.com/embed/LINK2';
                break;
            case 3:
                src = 'https://www.youtube.com/embed/LINK3';
                break;
            default:
                // For debug. But you should handle it.
                console.log("Error!");
        }
        document.getElementById('toChange').src = src;

        //All the <a> are no longer active.
        var as = document.getElementsByName('link');
        for (var i = 0; i < as.length; i++)
            as[i].className = "notActive";

        //The clicked is active now.
        document.getElementById(id).className = "active";
    }

    </script>
    </head>

    <body>
        <iframe id="toChange" width="560" height="315" src="https://www.youtube.com/embed/FirstLink" frameborder="0" allowfullscreen></iframe>

        <a id="1" name="link" onclick="change(1)">Video 1</a>
        <a id="2" name="link" onclick="change(2)">Video 2</a>
        <a id="3" name="link" onclick="change(3)">Video 3</a>
    </body>

    </html>

Here is the fiddle. I've created a single function that by using id of each element can change its class instead of several functions.