Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Detect element content changes with jQuery

change() function works and detects changes on form elements, but is there a way of detecting when a DOM element's content was changed?

This does not work, unless #content is a form element

$("#content").change( function(){     // do something }); 

I want this to trigger when doing something like:

$("#content").html('something'); 

Also html() or append() function don't have a callback.

Any suggestions?

like image 795
Elzo Valugi Avatar asked Jul 07 '09 10:07

Elzo Valugi


People also ask

How to detect content change in jQuery?

To observe and act on changes to a particular element, just modify the changeHtml function to use 'elem. trigger(...)' instead of 'jQuery. event. trigger(...)', and then bind to the element like $('#my_element_id').

How to detect div content change in Javascript?

The changes to the html/text of a div can be detected using jQuery on() method. The on() is used to attach one or more event handlers for the selected elements and child elements in the DOM tree. The on() method is the replacement of the bind(), live() and delegate() method from the jQuery version 1.7.


1 Answers

I know this post is a year old, but I'd like to provide a different solution approach to those who have a similar issue:

  1. The jQuery change event is used only on user input fields because if anything else is manipulated (e.g., a div), that manipulation is coming from code. So, find where the manipulation occurs, and then add whatever you need to there.

  2. But if that's not possible for any reason (you're using a complicated plugin or can't find any "callback" possibilities) then the jQuery approach I'd suggest is:

    a. For simple DOM manipulation, use jQuery chaining and traversing, $("#content").html('something').end().find(whatever)....

    b. If you'd like to do something else, employ jQuery's bind with custom event and triggerHandler

    $("#content").html('something').triggerHandler('customAction');  $('#content').unbind().bind('customAction', function(event, data) {    //Custom-action }); 

Here's a link to jQuery trigger handler: http://api.jquery.com/triggerHandler/

like image 169
Kyle Cureau Avatar answered Sep 27 '22 22:09

Kyle Cureau