0

So i'm sure this is a pretty easy solution but for some reason I can't get a solution that works.

I have a cloned div that I need to add a click event to. The function that I am trying to bind to each cloned div is the following:

function allowLike(songId){
  $('.queueTrack').off('click').on('click', function(){
    console.log('clicked like');
    console.log(songId);
    $.getJSON('/user', function(data){

      var token = data.token;
      songId = songId;

      $.ajax({
            url: 'https://api.soundcloud.com/me/favorites/' + songId + '?oauth_token=' + token,
            type: 'PUT',
            success: function(result) {
                console.log('u liked' + songId)
            }
        });
    })
  })
}

My problem occurs when cloning the div. During the clone I am resseting the id to a new one and need to use the old id as the argument for the allowLike(songId) function.

What I've done to try and get that id is below:

var songId = this.id; //This is the id I need for the function
console.log(songId) // this logs correctly
var cloned = $(this).clone(); //cloning the div
cloned.attr("id", queueList.length - 1); //changing the div's id to a new one
$("<span class = 'soundHover'><div class='soundMove'><i class='moveUp fa fa-arrow-up'></i><i class='moveDown fa fa-arrow-down'></div></i><span class='deleteQueue'><i class='fa fa-times'></i></span></span>").prependTo(cloned); //add some stuff to the new cloned div
$(cloned).appendTo(".queueListDiv").addClass("animated flipInX, queueTrack").removeClass('track'); //add the cloned div to it's new location

allowLike(songId); //call the allowLike function to bind click event

Now, this works fine and dandy if I clone the div and then click on it. It does everything great. The problem occurs when I clone multiple divs in a row and then try and click on them, they are all bound with the same songId argument instead of each having their own.

Any ideas?

Elliott McNary
  • 1,149
  • 3
  • 11
  • 20

1 Answers1

2

Rather first of all use an attribute to save songID named data-songid to the element, as in HTML you can have single id assigned to the element, this way you can just clone the element and put in the view easily, hope this helps, let me know if you are still not clear.

More reference about data attributes and here you get API

Community
  • 1
  • 1
Parag Bhayani
  • 3,280
  • 2
  • 28
  • 52
  • 1
    This worked great. Wasn't aware of data attributes. Thank you!! – Elliott McNary Jan 20 '16 at 12:17
  • In case anyone else sees this keep in mind that the data attribute should be in all lowercase – Elliott McNary Jan 20 '16 at 12:43
  • True, @ElliottMcNary The reason is attribute names are not case sensitive, and having uppercase lowercase will give feel like it is case sensitive, so to avoid such misconception always have attributes in lowercase – Parag Bhayani Jan 20 '16 at 13:15