Trigger a function upon the addition or removal of a CSS class

Introduction - no jQuery allowed!

I am in search of a way to track changes made to a specific DOM element that I can access using:

var el = document.getElementById('the-element');

Whenever a CSS class is added or removed from the el, I need the name of the CSS class to be sent to a function.

I am open to alternative solutions that are practical and effective.

For instance:

el.onClassChange(updateFunction);

function updateFunction(classname, status) {
    console.log('The classname is '+classname+' - '+status);
}

Answer №1

<!DOCTYPE html>
<html>
<body>

<p id = "elementToChange" changing=false>Press the button to activate a function that will display "Hello World" in a p element with id="output".</p>

<button onclick="modifyElement()">Click here</button>

<p id="output"></p>

<script>
function modifyElement() {

 var targetElement = document.getElementById("elementToChange");

 targetElement.classList.add("newClassName"); 
 targetElement.changing = true;

 targetElement.onchange();
}

document.getElementById("elementToChange").onchange = function(){
  if(this.changing){
     alert("Element modified");
     // perform an action upon element modification
     this.changing = false; // reset the changing indicator attribute
  }
}


</script>

</body>
</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am experiencing issues with my camera not capturing photos

My camera is not taking photos with expo-camera. It worked fine in the Android emulator, capturing photos and logging their values. However, when I tried using a real Android device, it failed to capture photos or log any values. Does anyone have a solut ...

Is it possible to implement a validation process that prevents the opening of a modal using data-bs-target until all necessary

I am currently using bootstrap version 5.2.3 and I have encountered an issue where the modal opens regardless of validation rules being met or not. I attempted to modify the data-bs-toggle and data-bs-target attributes using Vue.js, but the changes did no ...

Issue with Socket.IO: socket.on not executed

Recently, I devised a custom asynchronous emitter for implementing a server -> client -> server method. Regrettably, the functionality is not meeting my expectations. Although it emits the event, it fails to execute the callback as intended. Upon a ...

Is there a way to convert a PHP array into a JavaScript object and return it?

When I have an array defined and encode it using json_encode() $array = array("a" => "element1", "b" => "element2"); echo json_encode($array); The usual JSON output is: {"a":"element1","b":"element2"} However, my interest lies in getting this out ...

Why does IntelliJ IDEA 2016 show an error for using the [ngSwitch] attribute in this Angular2 template?

Every time I run precommit inspections, I receive a barrage of warnings even though everything seems to be functioning properly. The warnings include: Warning:(8, 58) Attribute [ngSwitch] is not allowed here Warning:(9, 42) Attribute [attr.for] is not all ...

js-libp2p works by establishing connections between nodes without initiating a new stream

To access the complete source code, visit this link: https://github.com/Gbr22/p2ptunnel listener: $ node listener.js The listener is ready and actively listening on: /ip4/192.168.0.101/tcp/10333/p2p/QmcrQZ6RJdpYuGvZqD5QEHAv6qX4BrQLJLQPQUrTrzdcgm /ip4/1 ...

How can I eliminate the CSS value that was inherited?

Looking for a way to eliminate the effect of an inherited CSS property with Jquery. .class1 #id1 div.class2 input.class-input{ border-color: #bbb3b9 #c7c1c6 #c7c1c6; } Can someone explain how to delete this "border-color"? Thanks. ...

I have a flex box with an image and text line inside. How can I adjust the width of the box and text to automatically match the size of the image?

Consider the code snippet below: <style> .img_box { display: flex; } </style> <div class=img_box> <img src=img/> <div>Title text of varying length. It may exceed the image's width or be smaller.</div> & ...

Scrolling feature is not effective in lower resolutions

At resolutions lower than 1024x768, the browser scroll is not functioning correctly. If you look closely, you will see that when the resolution is smaller, the purple stripe is not fully visible. I also observed that the body is positioned at the top, whi ...

Arranging my table

I've been trying to adjust the position of a table in my project that contains an image. Currently, it is aligned to the left and I want to move it to the right. Here is the code for my table: <TD> <IMG SRC='http://farm8.staticflickr.co ...

Dynamic navigation menu with Bootstrap's responsive multi-level design

I recently developed a multi-level navigation menu using Bootstrap. Everything seems to be working smoothly when the screen size is 1200px or above. However, I encountered an issue with the second level dropdown menu not opening upon clicking on screens sm ...

Script for migrating MongoDB attributes to an array

I am in the process of creating a database migration, and the current structure is as follows: { "site" : { "name" : "siteName1" }, "subStages" : [ "subStage1", "s ...

Waiting for the initial render before using document.getElementById() in next.js

I followed a tutorial that demonstrates how to access a canvas element by id using plain JavaScript. The tutorial can be found here. In the video, the method is explained around 5:10 and I adapted it for next.js in the code snippet below. import React, { u ...

Using Selenium to interact with a Modal Dialog window

When trying to navigate to a page in IE9 using Selenium, a certificate error message appears on the page. By using AutoIT, I am able to click within the browser, TAB twice, and hit enter without any issues. However, after this step, an error for a "Modal d ...

A subtle X icon tucked away in the corner of the homepage, a result of the jquery modal window

Struggling with an issue on a client's website - there are multiple jquery sections with buttons that open modal windows. The problem is that the close button for these modals appears on page load and is situated at the top right of the homepage. Is t ...

Translating a Javascript array into VBScript

I have encountered a challenge with my coding project - I have an array of objects created using Javascript, and now I need to access and manipulate it using VBScript. Unfortunately, I am struggling to figure out how to properly loop through the array in m ...

Guide to setting up a Cordova and TypeScript project using the command line interface

For my mobile application development, I rely on Cordova and execute cordova create MyApp in the command-line to initiate a new project. I am familiar with JavaScript but now require TypeScript for my project. Please assist me in setting up a Cordova pro ...

Create a d3 map specifically for a selected region based on the provided latitude and longitude coordinates

I am currently working on developing a d3 map inspired by the codepen created by Andy Barefoot: https://codepen.io/nb123456/pen/zLdqvM?editors=0010. My goal is to adjust the initiateZoom() function in a way that setting specific lat/lon coordinates for a b ...

Is it possible to manipulate videos embedded in an iframe using javascript?

It's common knowledge that JavaScript commands from Google can be used to control YouTube videos, while Vimeo provides its own JavaScript commands for their videos. Both videos are typically embedded within 'iframes' on websites. I'm ...

Function for calling a CSS callback with jQuery

I am currently working on enhancing my search bar using jQuery, and I am also looking to hide the navigation links. Here is a snippet of the jQuery code I have been using. The code functions properly when focused. $(".searchBox input").focus(function(){ ...