Click function getting old data attribute value - JQuery

371
April 12, 2017, at 6:03 PM

I have a standard click function in jQuery,

$( ".related-play" ).click(function() {
  $('#playlist .panel-collapse').removeClass('in');
  track_id = $('.related-play').data('id');
  $('#collapse-' + track_id).addClass("in");
  $('#collapse-' + track_id + " li").removeClass("active");
  $('#collapse-' + track_id + " .related").addClass("active");c
  console.log(track_id);
}); 

HTML

<div id="collapse-1156” class="panel-collapse collapse”>
    <ul class="nav nav-tabs inside-track-tabs">
           <li class=“active stems"><a data-toggle="tab" href="#stems-1156">Stems</a></li>
           <li class="related"><a data-toggle="tab" href="#related-1156">Related Tracks</a></li>
    </ul>
<div class="tab-content inside-track-content”>
    <div id=“stems-1156" class="tab-pane fade"></div>
    <div id="related-1156" class="tab-pane fade"></div>
</div>
<a class="related-play" data-id="1156">RELATED</a>

Separate to this function I also have another function that alters the data-id attribute based off other events in the page, via the use of this jQuery line

trackID = 1567 (This is just an example but actually trackID is generated at random and could be any number of different IDs
)
jQuery(".related-play").attr("data-id", trackID);

For some reason, I click related-play once, and it grabs it fine for the first time, however when I click it again, after the data attribute has changed and it grabs the old value. I check the DOM and this data attribute has an updated value, its getting the old value.

I can't see why it would do this though

Answer 1

In jQuery, $(this) is used to refer to the current object

You need to give current reference object using this as below

$( ".related-play" ).click(function() {
  $('#playlist .panel-collapse').removeClass('in');
  track_id = $(this).data('id'); // Change applied
  $('#collapse-' + track_id).addClass("in");
  $('#collapse-' + track_id + " li").removeClass("active");
  $('#collapse-' + track_id + " .related").addClass("active");c
  console.log(track_id);
}); 
READ ALSO
Ajax not redirecting to url

Ajax not redirecting to url

I am having issues to get a ajax GET method redirect me to a urlYesterday I had issues to passing data from my view to controller

292
Javascript - Remove an element from dynamic form

Javascript - Remove an element from dynamic form

I'm currently working on a form that has a "+' button that allows to display dynamically the same form again

349
Execute Javacript, into the divs opened previously with Jquery/javascript

Execute Javacript, into the divs opened previously with Jquery/javascript

I am doing a comment systemYesterday I asked for the same problem in stackoverflow and I didnt get any answer

275
Get caret position in Editable DIV

Get caret position in Editable DIV

Note: I had tried other answers related to this questionBut not get the solution

276