Question

So I'm dynamicly creating a list of songs like this.

function createSongsList(number){
    clearDiv("songList");
    songListDiv = document.getElementById('songList')
    var active = ' active';
    var pause = ' pause';
    for (var i = 0; i <tracksList.length ; i++) {
        var text ="";

        if(i==number){
            $(songListDiv).append('<a href="#" class="list-group-item '+active+'" id="'+i+'"><h4 class="list-group-item-heading"><span class="glyphicon glyphicon-pause"></span>'+'   '+tracksList[i].title+'  '+'</h4><p class="list-group-item-text">'+text+'</p></a>');
        }
        else{
            $(songListDiv).append('<a href="#" class="list-group-item" id="'+i+'"><h4 class="list-group-item-heading"><span class="glyphicon glyphicon-play"></span>'+'   '+tracksList[i].title+'  '+'</h4><p class="list-group-item-text">'+text+'</p></a>');
        }

    };
    $(songListDiv).on("click", 'a', function (e) {
        console.log("ID of selected song: "+$(this).attr('id'));
    });
}

function clearDiv(divId){
    document.getElementById(divId).innerHTML="";
}

When I want to change the list according to which song is currently playing, I just call the method again where I clear the div where the dynamic list is created and creat the list again.

The problem is that some how the onclick event fires the same amount of times as the list is created. So when the list is created the first time, the onclick fires once. The next time I call the method, the onclick fires twice, etc. Why is that?

Should I create a new function where I only update the elements in the list I want to change and do something with the onclick eventhandler there? I'm stumped...

Was it helpful?

Solution

You are binding an event each time you click. While that is uneffective, i am proposing 2 options :

First option

Get the binding out of your function and write it like that :

$('#songList').on("click", 'a', function (e) {
    console.log("ID of selected song: "+$(this).attr('id'));
});

This should be placed when #songList is currently in the DOM. Maybe it is there when the DOM is ready or you are appending it yourself.

Second option

Turn off the event before adding another .on() :

$(songListDiv).off('click', 'a').on("click", 'a', function (e) {
    console.log("ID of selected song: "+$(this).attr('id'));
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top