Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save dotherightthing/865cbae2d2777b2a139eeed48a472e45 to your computer and use it in GitHub Desktop.
Save dotherightthing/865cbae2d2777b2a139eeed48a472e45 to your computer and use it in GitHub Desktop.
[Debugging DOM attributes using the debugger] #observer #mutation
/**
* @function debuggerOnAttributeMutation
* @summary Open the JavaScript debugger when a particular attribute is mutated on the target element.
* @public
*
* @param {boolean} debugMode - Whether debug mode is enabled (_options.debug)
* @param {external:jQuery} $elements - One or more elements to watch the attributes of
* @param {string} attribute - Attribute to watch for mutations on.
* @see {@link https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver}
*/
var debuggerOnAttributeMutation = function (debugMode, $elements, attribute) {
if (!debugMode) {
return;
}
$elements.each(function () {
var $element = $(this);
// The node that will be observed for mutations
var targetNode = $element.get(0);
// The mutations to observe
var config = {
attributes: true,
attributeOldValue: true,
childList: false,
subtree: false,
};
// Create an observer instance with a callback function
var observer = new MutationObserver(function (mutationsList, observer) {
$.each(mutationsList, function (i) {
var mutation = mutationsList[i];
if ((mutation.type === 'attributes') && (mutation.attributeName === attribute)) {
debugger;
}
});
});
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
// Later, you can stop observing
// observer.disconnect();
});
};
debuggerOnAttributeMutation(
true, $('.element').eq(0), 'aria-expanded'
);

Debugging DOM attributes using the debugger

Debugger watch expressions:

When the debugger has paused code execution, this refers to the MutationRecord.

You can use jQuery in these expressions too.

this.attributeName
this.oldValue
this.target.getAttribute(mutation.attributeName)
document.getElementById('b-dynamic-breakpoint-proxy-trigger-1').getAttribute('aria-expanded')

Alternatives

The debugger provides a tab for Event Listener Breakpoints. There is a checkbox for DOMAttrModified, but it doesn't provide the ability to only pause execution if a specific DOM Attribute is modified (which is what this script does).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment