user984003
user984003

Reputation: 29597

Add jquery listener to dynamically created element

I need to add a jquery listener to some dynamically created elements. I cannot for the life of me to get this to work. tag_options is not dynamic, its children are. I have tried three ways:

http://jsfiddle.net/nfe2f/

<div id = "tag_options">
    <div class = "tag_option">hover me</div>
</div>

The js:

// never works
$('#tag_options').delegate('.tag_option', 'hover', function(event){
 alert();
});


// never works
$("#tag_options").on("hover", "[class='tag_option']", function(event) {   
    alert();
});


// works if not dynamically created
$('#tag_options .tag_option').hover( function(){
    alert();
 });

Upvotes: 2

Views: 1243

Answers (5)

Bill Criswell
Bill Criswell

Reputation: 32941

There is no hover event anymore and delegate is being phased out in favor of on. You'd want to use mouseenter and mouseleave. I believe you're shooting for this:

$('#tag_options')
  .on('mouseenter', '.tag_option', function(e){
    /* Wax On */
  })
  .on('mouseleave', '.tag_option', function(e){
    /* Wax Off */
  });

If you wish to keep it in one on you can do what palaѕн suggests. I just wanted to make it a little easier to follow:

$('#tag_options').on('mouseenter mouseleave', '.tag_option', function(event){
  if ( event.type === 'mouseenter' ) {
    /* Wax On */
  } else {
    /* Wax Off */
  }
});

Upvotes: 2

Jake Aitchison
Jake Aitchison

Reputation: 1109

example to go with first answer:

$('#tag_options').on('mouseenter mouseleave','.tag_option', function(event){
    if(event.type == 'mouseenter'){
        alert('entering');
    }
    if(event.type == 'mouseleave'){
        alert('leaving');
    }
});

Upvotes: 0

A. Wolff
A. Wolff

Reputation: 74410

Other syntax possible, more readable IMO:

$('#tag_options').on({
    mouseenter:function(){/**/},
    mouseleave:function(){/**/}
},'.tag_option');

Upvotes: 0

rink.attendant.6
rink.attendant.6

Reputation: 46307

There is a mouseover event that you can listen for:

$('#tag_options').on("mouseover", ".tag_option", function(event) {   
    alert('hello world!');
});

jsFiddle

Upvotes: -1

palaѕн
palaѕн

Reputation: 73966

This happens since there is no .on("hover" event. You can use mouseenter or mouseleave like:

$(function () {

    // Attach Event
    // new way (jQuery 1.7+) - on(events, selector, handler);
    $('#tag_options').on('mouseenter mouseleave', '.tag_option', function (e) {
        alert(e.type);
    });

    // Create elements dynamically
    $('#tag_options').append('<div class="tag_option">hover me</div>');
});

FIDDLE

Upvotes: 2

Related Questions