2

I want to trigger an onClick event for an entire class of elements. Normally, I would do something like this:

$(".classy").click(function(){
    console.log("Replace this line with something useful!");
});

However, every element of this class has distinct data-attributes that I want to use inside the onClick function. For example:

<div className="classy" data-num={100}></div>
<div className="classy" data-num={931}></div>
<div className="classy" data-num={777}></div>

On the click of each element, I would want to log the data-num value. Is there any way to do this with jQuery's .click?

3
  • so what you want is the data-num of the div you click right.? Commented Jul 12, 2017 at 14:38
  • Just do this.dataset.num inside the event handler Commented Jul 12, 2017 at 14:44
  • The selector matches multiple elements, but the events don't get bound to the set as a whole, but to each individual element in that set. So triggering the event on one of those elements will not trigger the events on the other elements. Inside the function you will have one element that triggered the event, which is this. Commented Jul 12, 2017 at 14:51

2 Answers 2

9

Here you go with the solution https://jsfiddle.net/Lk0pnu8e/

$(".classy").click(function(){
    console.log("First Way: " + $(this).attr('data-num'));
    console.log("Second Way: " + $(this).data('num'));
    console.log("Replace this line with something useful!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="classy" data-num={100}>100</div>
<div class="classy" data-num={931}>931</div>
<div class="classy" data-num={777}>777</div>

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

Comments

0

This will work fine for you -

$('body').on('click','.classy',function(){
   console.log($(this).attr('data-num'));
});

Am using the body so that even you add the div using AJAX(dynamically) the click will work.

Comments

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.