How to Detect When an HTML Element's Class Changes

How can I detect when an HTML element’s class changes?

There are DOM events, but they are far from perfect and not available in most browsers. In other words: Not possible (reliably). There are hacks like intervals and checking it in each iteration, but if you need to do something like this, your design is probably screwed. Keep in mind that such things will be slow and that there will always be a delay. The smaller the delay, the slower the application. Do not do that.

How to track DOM element's class attribute changes and apply same on some element

If possible, hook into that other library to get a proactive notification from it when it shows/hides that div.

If you can't do that, you can use a mutation observer to watch for changes to the attributes on the element, and then show/hide your other element depending on whether that element has the relevant class.

Example:

// Your code
var observer = new MutationObserver(function() {
var source = $("#source");
var target = $("#target");
target.toggleClass("hide-div", source.hasClass("hide-div"));
});
observer.observe($("#source")[0], {attributes: true});

// This code emulates the library that you don't control
var handle = setInterval(function() {
$("#source").toggleClass("hide-div");
}, 800);
$("#btn-stop").on("click", function() {
clearInterval(handle);
});
.hide-div {
display: none;
}
<button id="btn-stop">Stop</button>

<div id="source">This is the source element that the library changes</div>
<div id="target">This is the target element that we update when the source element changes</div>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Detecting class change without setInterval

You can use a mutation observer. It's quite widely supported nowadays.

var e = document.getElementById('test')var observer = new MutationObserver(function (event) {  console.log(event)   })
observer.observe(e, { attributes: true, attributeFilter: ['class'], childList: false, characterData: false})
setTimeout(function () { e.className = 'hello'}, 1000)
<div id="test"></div>

How to check if a class in an html element with an ID has changed using jQuery

Change events only trigger for form elements when the value is changed for form elements, it won't trigger for an element like div when some attributes changed.

You can use MutationObserver for listening attribute change.

var $div = $('#navbarSupportedContent');
var observer = new MutationObserver(function(mutations) { console.log("Change detected"); if ($('#navbarSupportedContent').hasClass('show') == true) { console.log("Scroll is locked"); $('body').addClass('lock-scroll'); } else { console.log("Scroll is unlocked"); $('body').removeClass('lock-scroll'); }});
observer.observe($div[0], { attributes: true, attributeFilter: ['class']});
$div.click(() => $div.toggleClass('show'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script><div id="navbarSupportedContent" class="collapse navbar-collapse">abc</div>

JQuery Detect class changes

There is no event of class-added, you will need to track it yourself...

It can be done with an infinite loop with setTimeout to check if the class has changed.

function checkForChanges()
{
if ($('.slide-out-div').hasClass('open'))
$('.otherDiv').css('top','0px');
else
setTimeout(checkForChanges, 500);
}

You can call the function when you want, or onDOM ready:

$(checkForChanges);

How to observe changes in HTML classes to change the innerHTML property

    let detectSection, detectFooter, section, footer;
const numberShow = () => {
detectSection = document.getElementsByClassName('section fp-section active
fp-completely');
if(detectSection !== null){
section = detectSection[0].id;
}else{
detectFooter = document.getElementsByClassName('section fp-auto-height fp-
section active fp-completely');
footer = detectFooter[0].id;
}
const num = document.getElementById('inc');

if(section == 'section0'){
num.innerHTML ='<p>00.</p><b></b>';
} else if(section == 'section1'){
num.innerHTML ='<p>01.</p><b></b>';
}else if(section == 'section2'){
num.innerHTML ='<p>02.</p><b></b>';
}else if(section == 'section3'){
num.innerHTML ='<p>03.</p><b></b>';
}else if(section == 'section4'){
num.innerHTML ='<p>04.</p><b></b>';
}else if(section == 'section5'){
num.innerHTML ='<p>05.</p><b></b>';
}else if(section == 'section6'){
num.innerHTML ='<p>06.</p><b></b>';
}else if(section == 'section7'){
num.innerHTML = '';
}
}
setInterval(numberShow, 200);

check if element class have changed

$("#elemID").click(function() {
$("#div").removeClass('a');
$("#div").addClass('b');
if ($("#div").attr('class') == 'b') {
$("#div").append("<p>Hello</p>");
}
});

Or

$("#elemID").click(function() {
$("#div").removeClass('a');
$("#div").addClass('b');
if ($("#div").hasClass('b')) {
$("#div").append("<p>Hello</p>");
}
});

Listen to className changes on an element replaced by ng-content

You can use the MutationObserver Api

Something like this:

  ngAfterContentInit(): void {
this.changes = new MutationObserver((mutations: MutationRecord[]) => {
mutations.forEach((mutation: MutationRecord) => {
// this is called twice because the old class is removed and the new added
console.log(
`${mutation.attributeName} changed to ${this.input.nativeElement.classList}`
);
});
});

this.changes.observe(this.input.nativeElement, {
attributeFilter: ['class'],
});
}

Here is a stackblitz with it running https://stackblitz.com/edit/angular-ivy-tz5q88?file=src%2Fapp%2Fchild.component.ts

Detect if a sibling class changes within a Div through JQuery

You can use the DOMSubtreeModified event to track class changes. And note that your id #this1 is not unique in your examples. So your html is invalid ...

$(".form-item .mck-radio").on("DOMSubtreeModified", function() {    if( $(this).hasClass("checked") ) {       console.log("I'm checked now!");    }});
$("button").click(function() { $(".form-item .mck-radio:eq(1)").addClass("checked");});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-item"> <div class="mck-radio"> <div id="#this1">Click Element 1</div> </div> <div class="mck-radio"> <div id="#this3">Click Element 2</div> </div></div>
<button>add class</button>


Related Topics



Leave a reply



Submit