Reputation: 13626
I have this div declared in my html page :
<div class="ol-unselectable ol-layers" style="position: absolute; width: 100%; height: 100%; z-index: 0;">
</div>
At some point to the style in div element above display changed to none:
<div class="ol-unselectable ol-layers" style="position: absolute; width: 100%; height: 100%; z-index: 0; display: none;">
</div>
When to the div element added display: none; I need to fire this row:
alert("not displayed");
for this purpose, I need to create a listener that will fire alert when display changed to none.
My question is how can I make an event listener that listens is div style has display: none
attribute?
Upvotes: 0
Views: 1202
Reputation: 171690
Use a MutationObserver. The following includes comments and base code from MDN docs
// Select the node that will be observed for mutations
const targetNode = document.getElementById('test');
// Options for the observer (which mutations to observe)
const config = {attributes: true};
// Callback function to execute when mutations are observed
const callback = function(mutationsList, observer) {
// Use traditional 'for loops' for IE 11
for (let mutation of mutationsList) {
const {type, attributeName } = mutation;
if (type === 'attributes' && attributeName === 'style' && targetNode.style.display === 'none') {
console.log('Style is none');
}
}
};
// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);
// Start observing the target node for configured mutations
observer.observe(targetNode, config);
document.querySelector('button').addEventListener('click',(e)=>{
const {style} = targetNode;
style.display = style.display === 'none' ?'block':'none'
})
<button>
Toggle content
</button>
<div id="test">Content</div>
Upvotes: 1
Reputation: 1485
If the change in CSS is done with JavaScript, you can use a MutationObserver
to detect the change. It will call the given function every time DOM changes occur to the target element.
const target = document.querySelector('.ol-unselectable');
const observer = new MutationObserver(function(mutations, observer) {
for(let {type, target} of mutations) {
if (type === 'attributes' && target.style.display === 'none')
alert("not displayed")
}
})
observer.observe(target, {attributes: true})
target.addEventListener('click', () => target.style.display='none')
.ol-unselectable {
background: blue;
cursor: pointer;
}
<div class="wrapper">
<div class="ol-unselectable ol-layers" style="position: absolute; width: 50%; height: 50%; z-index: 0;">
</div>
</div>
Upvotes: 1