1

I have a list of links that are being created dynamically by another function they are in the form <a id="hi-1">test</a> <a id="hi-2">test</a> etc.

I am trying to target these links and bind click/mouseover events to them. The following is the code for targeting one of these link(#hi-1):

$(function() {

    $("#hi-1") .bind("mouseover", highlight);
    $("#hi-1") .bind("mouseleave", highlight);
            $("#hi-1") .bind("click", highlight);

    });
    function highlight(evt){
    $("p#p-1").toggleClass("highlighted");
    }

This should toggle the class name of .

I can't seem to get it to work, I believe it could be something to do with the fact that the links are created dynamically. However i have little jQuery experience and i may be going about it the wrong way.

Any Help is much appreciated.

3 Answers 3

5

Selectors apply at the time of creation. You select the elements, then you bind to those elements, not to the selector.

You can, however, make use of event bubbling -- ancestor elements are notified of events on child elements. jQuery provides a beautiful syntax for this with delegate:

$('#containerElement').delegate('#hi-1', 'click mouseover mouseleave', highlight);

This assumes #containerElement is an ancestor element of all elements that will be matched.


However, if you only have one element (as is suggested by giving it an ID) it might be easier simply to bind the handler at the time the element is created.

2

Try

$("#hi-1").live("mouseover mouseleave click", function(){
    $("p#p-1").toggleClass("highlighted");
});
1
  • This worked for me, couldn't get my head around .delegate. Perfect, thank you
    – tcnarss
    May 28, 2011 at 9:55
2

You should use the .live() method of jquery.

http://api.jquery.com/live/

Attach a handler to the event for all elements which match the current selector, now and in the future.

Example:

$('.clickme').live('mouseover', function() {
    // live handler called
});
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.