Vincent Panugaling
Vincent Panugaling

Reputation: 906

jQuery Trigger mouseover event on newly created element

I wanted to trigger a mouseover event for an anchor tag(on the fly element)

jQuery(document).ready(function($){
    $('a.new_element').on('trigger("mouseover")', function(){
        do_my_stuff_here();
    })
})

EDIT: Yes, I figured out how to attach mouseover event on that anchor element, what I wanted is to trigger the mouseover event after a certain element is created on the fly(During Page load).

Any help would be greatly appreciated.

Upvotes: 0

Views: 563

Answers (2)

Derek 朕會功夫
Derek 朕會功夫

Reputation: 94409

To attach an event, use .on:

$("a.new_element").on("mouseover", ...);

To trigger an event on newly appended elements, use .trigger:

$("<a>").appendTo("body").trigger("mouseover");

If you really have to detect DOM change, use the DOMSubtreeModified event:

$("body").on("DOMSubtreeModified", function(){
    //However, determining "new" elements is another challenge.
    //Maybe the new MutationObserver could help
    somehowYouHaveTheElementsList.trigger("mouseover");
});

Upvotes: 2

Felix
Felix

Reputation: 38112

You need:

$('a.new_element').on("mouseover", function(){
    do_my_stuff_here();
})

or if you meant event delegation then you can do:

$('body').on("mouseover", 'a.new_element' , function(){
    do_my_stuff_here();
})

Upvotes: 1

Related Questions