Reputation: 531
I am at the moment working on a little extension to enhance a website namely the google plus post box. I want to move it to the very left of the monitor.
This post box however resets its values every time it is opened.
Basically I would like to kill off that behavior, and thought I could just monitor the element for element.style changes, and overwrite them again. However DOMAttrModified seems not to work for stuff like that
Additionally to that I have found that when the post box is closed it ceases to exist oO?
Maybe someone here has an idea how to tackle this I could of course just loop an operation that sets the style every second or so. but no thanks XD
thanks a lot for helping :)
Upvotes: 9
Views: 11313
Reputation: 206593
To get you quickly started with using Mutation Observer
here's a small reusable function
/**
* Mutation Observer Helper function
* //developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
* @param {string} sel The DOM selector to watch
* @param {object} opt MutationObserver options
* @param {function} cb Pass Mutation object to a callback function
*/
const Observe = (sel, opt, cb) => {
const Obs = new MutationObserver((m) => [...m].forEach(cb));
document.querySelectorAll(sel).forEach(el => Obs.observe(el, opt));
};
To track only attribute "style"
changes on some class="item"
Elements, use like:
Observe(".item", {
attributesList: ["style"], // Only the "style" attribute
attributeOldValue: true, // Report also the oldValue
}, (m) => {
console.log(m); // Mutation object
});
To watch for all attributes changes, instead of the attributesList
Array use :
attributes: true
If needed, here's an example:
/**
* Mutation Observer Helper function
* //developer.mozilla.org/en-US/docs/Web/API/MutationObserver/observe
* @param {string} sel The DOM selector to watch
* @param {object} opt MutationObserver options
* @param {function} cb Pass Mutation object to a callback function
*/
const Observe = (sel, opt, cb) => {
const Obs = new MutationObserver((m) => [...m].forEach(cb));
document.querySelectorAll(sel).forEach(el => Obs.observe(el, opt));
};
// DEMO TIME:
Observe("#test", {
attributesList: ["style"],
attributeOldValue: true,
}, (m) => {
console.log(`
Old value: ${m.oldValue}
New value: ${m.target.getAttribute(m.attributeName)}
`);
});
const EL_test = document.querySelector("#test");
EL_test.addEventListener("input", () => EL_test.style.cssText = EL_test.value);
EL_test.style.cssText = EL_test.value;
* {margin:0;}
textarea {width: 60%;height: 50px;}
<textarea id="test">
background: #0bf;
color: #000;
</textarea>
Upvotes: 5
Reputation: 32922
Mutation events are deprecated, DOMAttrModified is not and will not be supported by webkit browsers. Use Mutation Observers instead. Alternatively, you can try this workaround.
Upvotes: 9