Source : Stack Overflow – jQuery watch div.
Simulation JS Fiddle.
Le plug-in
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
jQuery.fn.contentChange = function(callback){ var elms = jQuery(this); elms.each( function(i){ var elm = jQuery(this); elm.data("lastContents", elm.html()); window.watchContentChange = window.watchContentChange ? window.watchContentChange : []; window.watchContentChange.push({"element": elm, "callback": callback}); } ) return elms; } setInterval(function(){ if(window.watchContentChange){ for( i in window.watchContentChange){ if(window.watchContentChange[i].element.data("lastContents") != window.watchContentChange[i].element.html()){ window.watchContentChange[i].callback.apply(window.watchContentChange[i].element); window.watchContentChange[i].element.data("lastContents", window.watchContentChange[i].element.html()) }; } } },500); |
Le code HTML
1 2 3 4 5 6 7 |
<p>Testing it: (click on divs to change contents)</p> <div id="a" onclick="$(this).append('i')">Hi</div> <div id="b" onclick="$(this).append('o')">Ho</div> <div class="c" onclick="$(this).append('y')">He</div> <div class="c" onclick="$(this).append('w')">He</div> <div class="c" onclick="$(this).append('a')">He</div> |
Utiliser le plug-in
1 2 3 4 5 6 7 8 |
function showChange(){ var element = $(this); alert("it was '"+element.data("lastContents")+"' and now its '"+element.html()+"'"); } $('#a').contentChange(function(){ alert("Hi!") }); $('div#b').contentChange( showChange ); $('.c').contentChange(function(){ alert("He he he...") }); |
Si le plug-in s’arrête de fonctionner après le 1er changement dans le DOM
Dans notre exemple, au clic sur une des options d’un élément HTML select
:
1 2 3 |
jQuery('body').on('click', 'select#product-declination > option', function(){ jQuery('div#b').contentChange( showChange ); }); |