If the div element undergoes a change, use an if-else condition to populate the data fields accordingly

I'm looking to create a basic if/else statement in JavaScript that checks if a div element has changed before populating JSON data fields/variables that pull from dynamically updated HTML.

I want to avoid using the deprecated DOMSubtreeModified method.

Below is my initial logic, but I need to find an alternative to DOMSubtreeModified and figure out how to nest my data array so it only populates after checking my if (condition). Any tips would be appreciated.

var element = document.querySelector('.username'); // username div wrapper

//if {

element.addEventListener('DOMSubtreeModified', function() { // detect if div element changes
  var date = new Date();
  var month = date.getUTCMonth() + 1;
  var day = date.getUTCDate();
  var year = date.getUTCFullYear();

  var time = date.toLocaleTimeString();
  var formattedDate = month + '/' + day + '/' + year;

  console.log(time); // 7:01:21 PM
  console.log(formattedDate); // 3/15/2016
}, false);

// change something on element
setTimeout(function() {
  element.dataset.username = 'bar';
}, 3000);

// json object with captured data fields

var NewUserSession = [{ 

    currentusername: $('.username').text(),
    referrer: document.referrer,
    loggedintime: $(formattedDate),

}];

//}
//
//else { 
//
//
//}

Answer №1

To monitor changes in the data-username attribute, you can utilize the MutationObserver API.

var element = document.querySelector('.username'); // Identify username div wrapper

var observer = new MutationObserver(function(mutations) {
  mutations.forEach(function(mutation) {
    if (mutation.attributeName === 'data-username') { // Check for specific attribute change
      var date = new Date();
      var month = date.getUTCMonth() + 1;
      var day = date.getUTCDate();
      var year = date.getUTCFullYear();

      var time = date.toLocaleTimeString();
      var formattedDate = month + '/' + day + '/' + year;

      snippet.log(time); // Output: 7:01:21 PM
      snippet.log(formattedDate); // Output: 3/15/2016
    }
  });
});

var config = {
  attributes: true,
  attributeFilter: ['data-username']
};

// Start observing the specified element with defined configuration
observer.observe(element, config);

// Simulate a change on the element after 1 second
setTimeout(function() {
  element.dataset.username = 'bar';
}, 1000);
<!-- Include the `snippet` object for logging results -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>
<div class="username"></div>

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

Every time I attempt to run "npm install" on Visual Studio Code, I encounter an error

Every time I try to run npm install, I encounter this error. My node version is 18.9.1 and I have exhausted all possible solutions. Any help would be greatly appreciated. '''npm ERR! code ENOENT npm ERR! syscall open npm ERR! path C:\Us ...

Compel the browser to launch a fresh tab

I'm currently working on an app that involves uploading files. One issue I'm facing is that the file system pop up doesn't close after the upload, causing a quarter of the screen to be covered while the test keeps running in the background. ...

Steps for Embedding an HTML Page into a Tab using jQuery

Within the tab labeled class=plots-tabs-heatmap, I am attempting to insert a new page using the code below. However, instead of seeing tmpdata/page2.html displayed on the tab, nothing appears. $('#plots-tabs-heatmap').html("tmpdata/page2.html"); ...

Flexible Magento layered navigation

Can anyone provide assistance on how to implement the collapse and expand functionality for Magento layered navigation? I have come across this code, but I am unsure of how to use jQuery with the dd dt class. <dl id="narrow-by-list"> <?php $ ...

Tips for passing two parameters to an event in JavaScript

I'm a bit confused on how to send 2 parameters for event listening in JavaScript and Vue.js. I am trying to edit input data when the keyup event is equal to 13 (enter), but I am unsure of how to send the event along with the value. When I try to send ...

Is it possible to upload an image file while the element is hidden with "display: none" property?

I need to upload a file using Selenium webdriver. Here is the URL of the page. <div class="async-upload__thumb item-image__area"> <div class="fab-dialog__thumb-drop-zone async-upload__thumb-drop-zone"> <p class="async-upload__thumb-ms ...

Tips for embedding text into a doughnut chart with primeng/chart.js

Currently tackling a primeng chart project involving the development of a doughnut chart within angular. The task at hand is to display text inside the doughnut chart, aligning with the designated design vision. Referencing the image below for visualizatio ...

Using Axios to retrieve data from a MySQL database is a common practice in web development. By integrating Vue

I have developed another Vue.js admin page specifically for "writer" where I can display post data fetched from a MySQL database. The admin page called "admin" is functioning properly and responding with all the necessary data. The following code snippet ...

Increase the value by one of the number enclosed in the <h3> element

I have a variable number of <h3> tags with the same class .love_nummer <h3 class="love_nummer">1</h3> Each of these tags contains a number, and alongside each .love_nummer tag is another tag with the class .give_love <h3 class="give ...

Free up MySQL connections within a Promise.All implementation

At the moment, I am facing issues with releasing MySQL connections from a connection pool. Interestingly, when I release connections in a synchronous "for" loop, everything works fine. However, when I attempt to release them asynchronously using Promise.Al ...

most effective method for recycling dynamic content within Jquery mobile

My jQuery mobile app has a requirement to reuse the same content while keeping track of user selections each time it is displayed. I have successfully created the necessary html content and can append it to the page seamlessly. The process goes something ...

Determine the frequency of a specific key in an array of objects

original array: ................ [ { from: {_id: "60dd7c7950d9e01088e438e0"} }, { from: {_id: "60dd7c7950d9e01088e438e0"} }, { from: {_id: "60dd7e19e6b26621247a35cd"} } ] A new array is created to count the instances of each ...

"Pressing the 'back' button on your browser takes

Is there a way to navigate back to the main page by clicking on an image? After selecting First, Picture1 will be shown. How can I go back to the selection page for further choices? <a href="picture1.jpg"> <h3>First</h3></a> <a ...

Error occurs when multiple checks are performed on the same script during form validation

I have recently developed a script that validates email addresses and checks for the availability of usernames. However, I am encountering an 'error on page' issue when I try to check both textboxes simultaneously. Strangely, if I test them indiv ...

Tips for smoothly animating and showing content as the user scrolls to a specific element on the page

Here is a sample template: <template> <div id="Test"> <transition name="fade"> <div class="row" id="RowOne"> <p>Lorem ipsum dolor odit qui sit?</p> </div> ...

Deactivate the button once it's been used | Discord.js version 14

In my index.js, I created a function to respond when a button is pressed and then disable it. client.on("interactionCreate", async (interaction) => { if (interaction.isButton()) { if (interaction.customId === "yes") { co ...

Showing an image stored in an array using JavaScript

This script is designed to pull images from a specific location on an HTML page. images = new Array(); images[0] = new Image(); images[0].src = "images/kate.jpg"; images[1] = new Image(); images[1].src = "images/mila.jpg"; document.write(images[0]); I&a ...

Using javascript to store HTML tags in a variable

Hey there, I have a quick question. Can someone help me figure out why this code isn't working? let plus = "+" + '<h1>'+"This is a heading"+'</h1>'; When I run the code, the output I get is: +<h1 ...

Interacting with the header component within the renderHeader property of the MUI Data Grid Pro will update the sortModel

Currently, I am utilizing the Material UI DataGridPro component to construct a React Js application. I am interested in developing a customized filtering feature. In the image below, you can see a red box representing an IconButton for the filtering view ...

What is the best way to embed HTML code within an amp-list component?

I was working with a json file that looked like this: { items: [ { FullImage: "87acaed5c90d.jpg", Title: "sometext", description: "<p id="imagenews"><img src='something'></p>" , } ] } I wanted ...