0

This works fine:

$('.classname').click(function() {
  alert('');
});
<div class="classname">Click me!</div>

But this doesn't:

$('.classname').click(function() {
  alert('');
});
<div class="classname">Click me!</div>
<div class="classname">Click me!</div>

How can i fix this? Thanks for your help! (The script in tags, and the .click is in a document ready function)

4
  • 8
    That should work fine. Are you adding the extra elements dynamically? Commented Feb 7, 2013 at 11:59
  • 1
    Your code is working, check it here, jsfiddle.net/rajaadil/WsXBk Commented Feb 7, 2013 at 12:01
  • Can you clarify what you mean by "doesn't work"? Do you have any console errors? This code should work fine. Commented Feb 7, 2013 at 12:06
  • did you insert any node dynamically after page loaded, just as @JamesAllardice guessed? if so, please update your question. Commented Feb 7, 2013 at 12:19

4 Answers 4

2

Just try this:

$('PARENTNODE').on('click', '.classname', function() {
  alert('');
});
<div class="classname">Click me!</div>
<div class="classname">Click me!</div>

The elements are added after your click handler is attached. By using .on() you enable it for future elements too.

Replace PARENTNODE with the parent you want to delegate to (eg. body)

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

Comments

0

You're trying to target elements that don't exist at the moment where .click is called.

You could wrap the whole jquery code between $(function() { your code here }); or move the javascript after the two <div>.

1 Comment

The OP says that it works with one div so this is unlikely to be the problem.
0

I'm assuming that all the divs but the first one are added dynamically.

Use an event delegated approach:

$(function(){
    $(document).on('click', '.classname', function() {
        alert('');
    });
}),

1 Comment

The order of the arguments is wrong. You have to flip '.classname' and 'click'
0

Try this

$(document).ready(function(){
    $(document).on('click', '.classname', function() {
      alert('');
    });
});

Refer http://api.jquery.com/on/

2 Comments

How is that going to make any difference? That's exactly what jQuery does behind the scenes anyway.
Refer answer here stackoverflow.com/questions/8601482/jquery-on-vs-click-methods

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.