0

This is the workflow:

  1. Add elements dynamically to a div container
  2. Register click event for this elements (using jquery custom function)
  3. Trigger the element event

According to the flow above, I can't get the new element event works, because it never is triggered. This is my scenario:

http://jsfiddle.net/9Ru76/1/

The idea is that when you click over "element" its ID attribute should be printed in .log div

Edit:

I have tested all answers and all of them work fine :)

3 Answers 3

3

You had the $(".element").showID(); outside the .create click handler so there was nothing to select, also you had your code in onLoad when it should be in no-wrap head.

http://jsfiddle.net/9Ru76/9/

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

5 Comments

Each call to showID will re-bind the event to the previous elements.
@Rocket I added a filter to select only the last one will bind a handler but then the ids are duplicate and the process could be done more efficiently.
FYI: the id is generated by another function that have no importance in this scenario
You can also create the new element first, bind the event, then use appendTo. That way, the events wouldn't get re-bound. jsfiddle.net/9Ru76/10
@Rocket, nice trick: .showID().appendTo(. Now suppose that .element elements are already added becasue they come from removeClass('something').addClass('.element'). In this case, Does the event delegation works as the same way? PS: Do I need to open a new question?
1

You can use event delegation

$(document).ready(function(){

    $(".create").click(function(){
         $(".container").append('<div id="4" href="#" class="element">element</div>');
    });
});


    $(document).on('click','.element', function(){
        $(".log").html("id: " + $(this).attr("id"));
    });

Comments

0

In jsFiddle, the code is automatically put in a $(document).ready block. So, what's happening is your $(document).ready is ran immediately. This means it's ran before jQuery.fn.showID is set.

Also, $(".element").showID();​ binds the event to .elements that exist at that time. New elements won't have the event bound. You need to either use event delegation (which makes the showID plugin useless), or call showID after adding the element (making sure not to re-bind to old elements).

P.S. Inside a jQuery plugin this is already a jQuery object, no need to use $(this).

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.