Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do an action when an element is added to a page using Jquery?

When I add something of the class "myClass" I want to call a function on this element.

It would be something in the lines of:

jQuery(".error_message").live("load",function(){
  alert("test"+this);
});

... except this doesn't exist.

What's the best way of doing this?

like image 212
marcgg Avatar asked Sep 29 '09 02:09

marcgg


People also ask

Which method is triggered when an element is added to the DOM?

We can detect if an element has been added to DOM using the MutationObserver object. This provides the ability to observe for changes being made to the DOM tree.

Which jQuery will you use if there is a need to insert specified content after a selected element?

jQuery after() Method The after() method inserts specified content after the selected elements.

What is $() in jQuery?

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the element(s). Basic syntax is: $(selector).action() A $ sign to define/access jQuery. A (selector) to "query (or find)" HTML elements. A jQuery action() to be performed on the element(s)

Which jQuery method is used to add content to a page?

Add New HTML Content We will look at four jQuery methods that are used to add new content: append() - Inserts content at the end of the selected elements. prepend() - Inserts content at the beginning of the selected elements. after() - Inserts content after the selected elements.


1 Answers

The short, direct answer to your question would be "no can do." But from your comment a few minutes ago, I see that you want to add elements in different ways and have one unified method of handling these newly added items. May I suggest another approach? Trigger custom events.

The way it would work is like this: everywhere you load the error-message element, you add one line when it's done:

 $('.error_message').trigger('load');

Now your .live('load'...) thing will work.

like image 57
Barnabas Kendall Avatar answered Oct 13 '22 02:10

Barnabas Kendall