Maintain the markup created by jQuery inside the AJAX function called by setInterval

In the code snippet below, real-time markup is generated and automatically updates using the setInterval function. The markup includes buttons and hidden content within div elements. Each button reveals its corresponding div, but the div reverts to a hidden state after each interval refresh. I am looking for a way to retain the visibility of a particular div even after the interval refresh, especially after it has been clicked. Is there a method in front-end JavaScript to remember which div was previously shown before the interval refresh? Please note that I am seeking a solution without involving server-side operations. Thank you!

setInterval(itemMenu,1500);

function itemMenu() {

    $.ajax({
        type: "GET",
        url: "Administration/data/people.xml"
    }).done(function (xml) {

        $("#loadMe").empty();
        $("#toadMe").empty();

        $(xml).find('fullName').each(function(index) {

            // Generate markup for 'loadMe'
            var i = index + 1;
            var fullName = $(this).text();

            $('<button type="button" class="mybutton" name="users" onclick="itemContent(this.value)"></button>').attr('value', i).html(fullName).appendTo('#loadMe');

            // Generate markup for 'toadMe'
            var firstName = $(this).siblings('firstName');
            var lastName = $(this).siblings('lastName');
            var age = $(this).siblings('age');
            var hometown = $(this).siblings('hometown');
            var job = $(this).siblings('job');

            $('<div></div>').attr('id', i).appendTo('#toadMe');
            $('<h1></h1>').html(firstName).appendTo('#' + i);
            $('<h1></h1>').html(lastName).appendTo('#' + i);
            $('<h1></h1>').html(age).appendTo('#' + i);
            $('<h1></h1>').html(hometown).appendTo('#' + i);
            $('<h1></h1>').html(job).appendTo('#' + i);

            $('#'+i).hide();

        });
    }).fail(function (response, error) {
        $('#info').text('Error!');
    });

};

function itemContent(k) {
    $("#"+k).show();
};

Answer №1

Have you thought about creating the <div> dynamically only when the button is clicked, instead of constantly replacing those elements when polling the XML? Here is a possible solution:

setInterval(refreshXml, 1500);

function refreshXml() {
  var req = $.get('Administration/data/people.xml');

  req.done(function(xml) {
    window.peopleXml = xml;

    $('#loadMe').empty();

    $(xml).find('fullName').each(function(index) {
      var fullName = $(this).text();

      $('<button>', {
        'class': 'mybutton',
        value: $(this).siblings('id').text(),
        text: fullName
      }).appendTo('#loadMe');          
    });

    $('#toadMe .person').each(function() {
      var id = $(this).data('person-id');

      show_person(id);
    });
  });
}

function show_person(id) {
  $('#person-detail-' + id).remove();

  get_person(id).appendTo('#toadMe');
}

function get_person(id) {
  var $person = $(window.peopleXml).find('id:contains(' + id + ')').parent();

  var $div = $('<div>', {
    'class': 'person',
    'data-person-id': id,
    id: 'person-detail-' + id
  });

  $('<h1>', { text: $person.find('firstName').text() }).appendTo($div);
  $('<h1>', { text: $person.find('lastName').text() }).appendTo($div);
  $('<h1>', { text: $person.find('age').text() }).appendTo($div);
  $('<h1>', { text: $person.find('hometown').text() }).appendTo($div);
  $('<h1>', { text: $person.find('job').text() }).appendTo($div);

  return $div;  
}

$(document).on('click', '.mybutton', function() {
  show_person(this.value);
});

With a growing XML file, this method will be more efficient even if it may seem complex initially. Constantly pre-generating a <div> for every potential person every 1.5 seconds could significantly slow down the browser as the XML document increases in size.

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

Using jQuery to toggle a class on the appropriate element

Currently trying to master jQuery, specifically toggleClass. Main Objective: Load a div with a fixed height and hide the overflow... by clicking an element, the full content of the div should be revealed. Similar to an accordion, but with the initial part ...

What common problems arise from using mutable data types in a single-threaded environment?

In JavaScript, concurrency is modeled by an event loop, eliminating race conditions. Given this, what are the potential downsides of performing a type-safe operation in the main scope of a program that would warrant caution? const m = new Map([["foo", tru ...

Struggling to retrieve the value in Node.js

Currently, I am in the process of developing a Node.js script to perform the following tasks: Read a file line by line Identify a regex match and store it in a variable Utilize this value in subsequent operations Below is the code snippet that I have im ...

Utilize CSS to specifically target the image source within a button and swap it with a different image in the Woocommerce Wishlist Plugin on your Wordpress

I have integrated the Woocommerce Wishlist plugin into my Wordpress website and I am looking to customize the appearance of the 'Add to Wishlist' button. Upon inspecting the source code, I noticed that the button is styled with a GIF image. I wou ...

Automatically Refresh a Div Element Every 5 Seconds Using jQuery's setInterval() Function

My goal is to refresh the left div every 5 seconds using $.ajax to get JSON data and display 4 random elements in that div. However, even though the left div block refreshes, the content remains the same with the same images always showing. view image desc ...

Transferring form data to a PHP script with the help of JavaScript/jQuery

Struggling to figure out how to pass form values to a PHP script using JS. The PHP script is functioning correctly by saving the data into a text file with additional information such as IP and Date/Time. Despite being a simple issue, my lack of JS knowl ...

Tips for managing unexpected TCP disconnects?

Using Node.js, I set up both a TCP server and an HTTP server. The TCP server was intended to connect with hardware devices via TCP connection. I have 100 TCP clients that are maintaining their connections with the server. Normally, when a TCP client disc ...

Ensuring elements are correctly positioned

I am struggling to make the images in the following code align horizontally across the top and also need to align the h1's in the same way. I have tried using the vertical-align property, but it seems to behave oddly to me. HTML: <div class=&apos ...

Animations and transitions for cards

import Section from '@/components/section' import {Card, CardHeader, CardBody, CardFooter, Divider, Link, Image, Button} from "@nextui-org/react"; import { CSSProperties, useState } from 'react'; const Index = () => { c ...

Using React Native to share API and passing a Base64 string in place of an image when sharing to WhatsApp

I am facing difficulties in sharing a base64 image on WhatsApp. On both iOS and Android, the actual base 64 code is shared instead of the image. When I try to use iMessage or Email on iOS, the base64 images are converted and displayed correctly. However, ...

The error message "Uncaught ReferenceError: require is not defined" is commonly encountered when using Webpack

Despite countless similar questions, none have provided a solution to my issue because the underlying problem seems to elude me. I am attempting to bundle files for the browser using webpack 4.26.1, but no matter what I try, I consistently encounter the er ...

Utilize the Bootstrap responsive grid system to ensure that every row is filled with content, creating

I am working with a list of 8 results that I display in a responsive bootstrap grid. However, I want to only show the results that fill up entire rows. For instance, on a medium-sized screen, it appears as 2 rows with 4 results each. On a smaller screen, ...

Using Node.js and Express, the CSS does not load due to route parameters

I'm currently working on a basic website project using Node.js, Express, and the EJS template engine. I've run into an issue where my external CSS files are not loading properly on routes that contain route parameters. Here's a snippet of my ...

Creating a Dynamic Soundtrack: How to Embed an Audio

Success! I finally figured it out, with a little help from everyone. I've been diving into the world of Audio Playlists in HTML and attempted to follow a tutorial on the topic found here: https://www.youtube.com/watch?v=vtZCMTtP-0Y. However, I encoun ...

What is the best way to incorporate an expression into a package.json file?

Query: Is there a way to automatically increase the version in a script message? I need my release message to always be one version higher than the previous. Aim: For example, if I have version **0.1.2**, I would like to update my commit message to 0.1.3 ...

At 400 pixels screen size, the buttons in the appBar component are spilling out

In my appBar component, I have three buttons that appear fine on large screens. However, when the screen size reaches 400px, they start stretching out of the appBar. Here is how they look on large screens: https://i.sstatic.net/l3nJM.png And this is how ...

Aligning a button with a <div> block is not achieved through styling

Take a look at the jsfiddle example. Expected result: Actual result: Here is the HTML snippet responsible for that section of the page: <input type="submit" name="BT_resetZoom" value="Reset coordinates" id="BT_resetZoom" tabindex="10" style="height: ...

Guide on building a "like" button using a Node.js Express application

I am in the process of developing a website using node, express, and mongodb. I am facing an issue with passing a variable value from my ejs file to the server side. Can someone help me solve this problem? Here is what I have attempted so far: Example Ht ...

Utilizing CSS to transform text with a sleek, animated writing effect

I have utilized CSS to create a captivating animation effect where text is written out in a smooth style. I am seeking assistance in replacing the current text with a different one while maintaining the same effect. HTML & CSS .typed-out{ overflow: ...

Feature of Thymeleaf: Download functionality

When working with my Thymeleaf template, I have successfully processed Java map content to HTML using the following code: <div th:each="file : ${files}"> <span th:text="${file.key}"></span> <!-- here file.key is retrieved --> ...