Thursday, August 22, 2013

jquery event on addClass or show/hide

Its often require to fire some event when new class is getting added to the element, or when element is moving from hidden state to visible state or otherwise.

I come across similar scenario while rendering graph using jqplot library. Though if you have div hidden and you try to plot the graph on it, it won't display the graph when you make the parent variable visible. In similar situation it requires replot (which is basically redraw of the element.)

As there is no 'hide' event in DOM, so we will not be able to bind the event. Other way to resolve this issue is by Javascript MutationObserver. In which you can select target node (element) and observer instance.

Though you can find many complex solution on web, here is the simple and neat way to do it using jQuery.

Lets say you have element with class 'xyx', and upon making it to visible you would like to fire few more calls and refresh certain things on the page. You can do it using trigger -

$(".xyz").show();
$("xyz.").trigger('cssClassChanged');

The similar calss cssClassChanged needs to be listen somewhere that its been triggered, so its almost like publisher - subscriber model. Here is the sample -

$('.xyz').bind('cssClassChanged', function(){ perform your steps });


Easy and simple solution.