tags:

views:

62

answers:

5

I have a DIV where some code is presented. When I hover on this DIV I want to present a button that toggles the comments inside the code block. So far I have this:

$('.code-block').hover(
    function(){
        $(this).prepend('<span class="code-block-control">toggle comments</span>');
    },
    function(){
        $('.code-block-control',this).remove();
    }
);

$('.code-block-control').click( function(){ $('.comment').toggle(); } );

The span is presented when I hover over the code block. But when I click the span that is created nothing happens. Even if I change the click function to a simple alert nothing happens.

Anyone have any idea on how to fix this.

A: 

You must call the listener iterator again; the iterator only affects nodes already present at the time.

Delan Azabani
A: 

Use event delegation, jQuery offers live and delegate:

$('.code-block-control').live("click", function(){ $('.comment').toggle(); } );

Done.

karim79
+1  A: 

Use live():

$('.code-block-control').live('click', function(){
  $('.comment').toggle();
});

Since span is dynamically generated, the click event won't work, you need live instead.

Live Description:

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

Sarfraz
Got it! Thank you
Saif Bechan
@Saif Bechan: You are welcome :)
Sarfraz
A: 

If you user prependTo you can assign the handler to the generated span

$('<span class="code-block-control">toggle comments</span>').
  click( function(){ $('.comment').toggle(); } ).
    prependTo(this);
RoToRa
A: 

You should just have the span already in the HTML instead of inserting it with your script. Then set the .hover() event to remove the `display: none" style.

This way you don't have to worry about setting your event handler every time. Plus you know it is going to be inserted most of the time, so it's not really "dynamic" in terms of the user context, just in terms of the user's action, so doing "display: none" is more appropriate, I think.

Anthony
Yeah this is true. But then I have to insert the span into every code block. And there are a lot of them, so the method of dynamic inserting saves me tons of time.
Saif Bechan