1

I have a Jquery on() handler with a click event. In the function I get the data attribute that is in the selector's a tag, like so:

$(document.body).on('click', '.video-thumbnail a' ,function(){
  var videoID =  $(this).attr('data-video-id');
  //more data atts etc.
});

My HTML is like so: (times ~ *20)

<div class="block">
    <div class="video-thumbnail">
      <a data-video-id="123"><img></a>
    </div>
    <div class="video-title">
      <a>title</a>
    </div>
    <div class="video-watch">
      <a>Watch</a>
    </div>
</div>

What I want to achieve is that every anchor in the div ".block" have the same click event handler, but I can still use the data-attr from the first anchor (either using this or something else).

So: no matter what anchor the user clicks on within that div; they all execute the same jquery function using the same data-attr.

What is the best way to do this?

Thanks guys.

1
  • It seems to me like you should alter your structure. The data-video-id attribute appears to belong to the whole .block and it might be more appropriate if it were an attribute of .block rather than of the anchor. Commented Nov 9, 2014 at 16:14

1 Answer 1

4

So, if I'm understanding correctly, you want to attach event handlers to all anchors, but always get the attribute from the .video-thumbnail <div>. You'd be best off using .closest():

$(document.body).on('click', '.block div a' ,function(){
    var videoID = $(this).closest('.block').find('.video-thumbnail a').attr('data-video-id');
})

Please note the other errors in your code:

  • You need a closing parenthesis at the end of your jQuery
  • You need to close your class attribute on your .video-thumbnail element.

As already mentioned by 76484 it would semantically make much more sense to have each block hold the data-video-id attribute, since that is the upper-most context for each video.

Sign up to request clarification or add additional context in comments.

2 Comments

I will try that, thank you. You can ignore the errors in the code, I just wrote it quickly for this post to get the point across.
@Cooleronie Glad to have helped.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.