Is it possible to determine if a style property has been altered

I am looking to identify changes in CSS properties without needing the actual values. I only require the specific style property that has been altered. For example, I need the style property to be stored in a variable, as shown below:

document.getElementById('id1').style.backgroundColor = 'red';

document.getElementById('id1').style.color = 'red';

I have attempted using a MutationObserver with a style filter, but I am exploring other potential methods to retrieve the style property.

<h1 id="id1" style="background-color:green;color:blue;">My Heading 1</h1>
  
<button type="button" 
onclick="document.getElementById('id1').style.color = 'yellow'"> 
Click Me!</button>
  
<button type="button" 
onclick="document.getElementById('id1').style.backgroundColor = 'red'"> 
Click Me!</button>
const Observep = document.getElementById("id1");
  
const observerp = new MutationObserver(function() { 
// var styleproperty = (backgroundColor or color or width....) 
alert("id1 change" + styleproperty);
});

observerp.observe(Observep, {subtree: true, attributes: true});

Answer №1

Here is the solution you've been searching for:

const TargetElement = document.getElementById("id1");

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    //console.log(mutation.target.style)
    let styles = mutation.target.style;
    for(style of styles){
      console.log(style)
    }
    if(mutation.attributeName === 'style'){
      alert("style change");
    }
  });    
});

// Watch for changes in styles
var observerConfig = {
  attributes: true, 
  attributeFilter: ["style"]
};

observer.observe(TargetElement, observerConfig);
<h1 id="id1" style="background-color:green;color:blue;">My Heading 1</h1>;

<button type="button" 
onclick="document.getElementById('id1').style.color = 'yellow'">
Click Me!</button>;

<button type="button" 
onclick="document.getElementById('id1').style.backgroundColor = 'red'">
Click Me!</button>

Answer №2

Give this a shot:

<button type="button" onclick="applyStyles()"> Click Here!</button>


<script type="text/javascript">

    const item = document.getElementById("item1");
    var styles = { 
        backgroundColor:'red',
        color:'purple',
      }

    function applyStyles (){
      for(let property of Object.keys(styles)){
        console.log(property);
        item.style[property.toString()] = styles[property.toString()];
      }
    }

</script>

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

Animation of disappearing blocks covering the entire screen

I am currently working on creating a slider with fading blocks animation similar to the one shown here. The challenge I am facing is making it fullscreen, where the height and width will be variable. This makes using the background-position trick ineffecti ...

Can we effectively manage the input for a component that is created dynamically in real-time?

Please note: I am a newcomer to ReactJS, JavaScript, and the world of front-end development in general. Hello everyone, I have made the decision to create a versatile component that can handle all the forms within my project based on a predefined templat ...

Can you identify the animation being used on this button - is it CSS or JavaScript?

While browsing ThemeForest, I stumbled upon this theme: What caught my eye were the animation effects on the two buttons in the slider ("buy intense now" and "start a journey"). I tried to inspect the code using Firebug but couldn't figure it out com ...

Ways to prevent a page from scrolling

I'm currently working on a webpage that features a vertical drop-down menu. The issue I'm facing is that when the menu drops down, it causes the text below it to be pushed downwards and off the page. While this behavior is anticipated, it also tr ...

The submission of the form is not functioning correctly when triggered by JavaScript using a button

My website was designed using a CSS/HTML framework that has been seamlessly integrated into an ASP.NET site. Within a ContentPlaceHolder, I have implemented a basic login form. The unique aspect is that I am utilizing the onclick event of an image to subm ...

Changing the Input Label Color on Hover in Material-UI TextField

I have a custom styled Mui TextField called CustomTextField. It changes the input background color and font color on hover, but I also want to change the label font color when hovered over. Currently, the input background changes from black to white on hov ...

Can you show me a comprehensive list of all the REST endpoints for Express mounted Apps?

When working with Express 4, you can utilize the app._router.stack object to list your app routes. In one of the routes in my todos module routes file, I attempted to display this object by sending it as part of the response: exports.update = (req,res) = ...

Is there a way to update the background image of a div element through a JavaScript file within a react component?

After spending hours on this issue, I am still stuck and have exhausted all my ideas and research. In my project, I have three buttons that are supposed to change the background image of my site. The background image is linked to the default "App" div elem ...

Is there a way to send map data using props in React?

I just want to store and pass the current props.url to the videomodal so I can show the same active video on the video modal. I can't use useState in the map. How can I pass it? Or is there any other solution? Videos.tsx ( props.url must be in the &l ...

The HTML iframe is displaying blank content

I'm trying to embed a webpage within another webpage using an iframe. I attempted to do so with this simple code: <iframe src="http://edition.cnn.com/" id="i_frame"></iframe> JSFIDDLE However, nothing is displaying. Any thoughts on why ...

Generating dynamic dropdown menus using data from a database with the help of PHP and Ajax technologies

I'm currently working on creating a dynamic dropdown menu that will be populated with data retrieved from a database. I've hit a roadblock in parsing the data from a multidimensional array sent by a PHP file. Here's a snippet of my code: Se ...

What is the best way to display live data to multiple users with React and Firebase?

I'm working on a messaging app that needs to update in real-time. Currently, I have implemented the functionality to log in using Google, post messages, and display them on the screen. However, when another user logs in with a different Google account ...

Tips for successfully using `cols=""` within a grid container alongside a textarea

It seems that both Chrome and Firefox are not following the cols attribute on textarea elements within a grid container: .grid { display: grid; } textarea:not([cols]) { width: 100%; } <h2>Not in a grid container:</h2> <div> <tex ...

Preventing the element from breaking when it is not the child: Tips and Tricks

In order to align both .quote-container and #new-quote elements in the same line, even when the window width is very small (e.g., 83 pixels), I used min-width on the .quote-container element successfully. However, applying the same technique to the #new-qu ...

Aggregate X and Y values based on a key in a scatter plot using dc.js

Here is a glimpse of my dataset: var items = [ {name: "X", duration: 1, quantity: 2}, {name: "X", duration: 2, quantity: 1}, {name: "Y", duration: 1, quantity: 4}, {name: "X", duration: 3, quantity: 1 ...

Looking for a bootstrap table code that includes checkboxes and a save button, so that when the save button is clicked, it

Seeking a Bootstrap table code that includes row checkboxes. When the save button is clicked, it should return the selected checkbox rows. ...

A guide to leveraging Mongoose transactions when utilizing the updateMany method

While utilizing the mongoose updateMany() method within a transaction, I encountered some confusion. The documentation provides an example of using save() with a session, such as Model.save({session: mySession}), but I am unsure how to apply this to Model. ...

Using JavaScript variables within the value section of a JSON is a common requirement for developers

var averageTemperature = req.params.rating; var destinationName = req.params.name; var query = { "results.name": destinationName }; var updateQuery = { $set: { "results.$.rating": averageTemperature } }; mach.update(query, updateQuery, function(err, res ...

Triggering AJAX call from several buttons within a single page in Django

Hey there! I'm currently working on implementing a voting feature using Ajax in my Django-based website. The issue I'm facing is that users can only vote on the first entry, but I want them to be able to vote on all entries. Can you assist me wit ...

The integration of PHP code with an HTML form is causing issues

When I use the insert_teacher('bla bla','bla bla','dqsd') function in a PHP file, everything works fine. However, when I try to implement it with an HTML form, nothing is displayed and no data is inserted into my database. &l ...