Watching the DOM

Watching the DOM

Ever wanted to know when a DOM (Document Object Model) element has changed, but you are not the one changing it, so you don’t get an event to watch? We ran across this same issue just the other day. Here’s a quick tip on how we fixed it…

We were working with a slider component on our website and wanted to know when the slide changed so we could update other elements on the page. The problem was, the slider component didn’t provide an event we could observe. Enter the MutationObserver.

A mutation observer allows you to attach a callback function that is called when the DOM element it is watching changes. In our case, we wanted to be notified when one of the little dots on the bottom of the slider had an ‘active’ class added to it.

Check out the code:

	var controls = jQuery('.et-pb-controllers')[0];
	var mut = new MutationObserver(function(mutations, mut){
		mutations.forEach(function (mutation) {
			var el = mutation.target;
			var value = mutation.target.textContent;

			//do whatever you want here when the element changes

		});
	});
	jQuery("a", controls).each(function(){
		mut.observe(this,{
		  'attributes': true
		});
	});

Our callback handler is now called anytime the links element changes and we can update other parts of the page accordingly.

As an added plus, the MutationObserver has fairly wide browser support.

Submit a Comment

Your email address will not be published. Required fields are marked *