Dilemma arises from conflicting javascript codes

Currently, I am developing a web application where the main page features a timeline that needs to update its content automatically. To achieve this, I am utilizing the setTimeOut function of JQuery to refresh the timeline every x seconds.

In addition, there is another JavaScript code implemented to reveal hidden elements within that item when clicking on the respective div.

Both scripts work flawlessly independently, however, they encounter an issue when combined on the same page. The problem arises after the timeline is updated by setTimeOut; the second code responsible for toggling the visibility of elements upon clicking the div stops functioning. Despite trying various solutions, none have proven successful so far. If anyone has insights into this matter, it would be greatly appreciated. Furthermore, any suggestions on optimizing my timeline, such as updating only when new items are added instead of at set intervals, are also welcome.

setTimeout("my_function();", 9000);
    function my_function() {
      $('#timeline').load(location.href + ' #timeline')
    }

$(document).ready(function () {
      var itemsDivs = document.querySelectorAll('.timeline-item');
      itemsDivs.forEach(function (itemsDiv) {

        itemsDiv.addEventListener('click', function () {
          var itemId = this.getAttribute('item-id')
          var display = document.getElementById('comment-form-' + itemId).style.display
          if (display == 'none')
            document.getElementById('comment-form-' + itemId).style.display = 'block'
          else
            document.getElementById('comment-form-' + itemId).style.display = 'none'
        })
      })
    })
<div class="container-fluid">
    <div class="row example-basic">
      <div class="col-xs-10 col-xs-offset-1 col-sm-8 col-sm-offset-2">
        <ul class="timeline" id="timeline">
          {% for item in items %}
          <li item-id={{item.id}} class="timeline-item">
            <div class="timeline-info">
              <span>{{item.data.strftime('%c')}}</span>
            </div>
            <div class="timeline-marker"></div>
            <div class="timeline-content">
              <h3 class="timeline-title">{{item.analista}} recomenda {{item.ativo}} a R${{item.preco}}.</h3>
              <p>Fonte:{{item.fonte}}</p>
            </div>
            <div id="comment-form-{{ item.id }}" style="display: none;">
              {{item.coments}} <br><span id='dataalvo'>Data Alvo: {{item.dataalvo}}</span>
            </div>
          </li>
          {% endfor %}
          <li class="timeline-item period">
            <div class="timeline-info"></div>
            <div class="timeline-marker"></div>
          </li>
        </ul>
      </div>
    </div>

Answer №1

To ensure your event listeners are functioning properly, it is necessary to re-register them.

In Javascript, event listeners do not directly attach to a selector but rather to the specific elements themselves. The code

document.querySelectorAll('.timeline-item')
selects all DOM elements that currently match the .timeline-item criteria. After a 9-second delay (as per your setTimeout function), you remove all existing .timeline-item elements and populate the page with freshly updated ones using the load() method which replaces the inner HTML content.

If you want the newly added .timeline-item elements to have event listeners, they must be registered again. Below is an example of how this can be achieved:

setTimeout(function() {
    $('#timeline').load(location.href + ' #timeline', function() {
        registerEventListeners();
    });
}, 9000);

$(document).ready(function () {
    registerEventListeners();
});

function registerEventListeners() {
    var itemsDivs = document.querySelectorAll('.timeline-item');
    itemsDivs.forEach(function (itemsDiv) {
    
        itemsDiv.addEventListener('click', function () {
            var itemId = this.getAttribute('item-id')
            var display = document.getElementById('comment-form-' + itemId).style.display
            if (display == 'none')
                document.getElementById('comment-form-' + itemId).style.display = 'block'
            else
                document.getElementById('comment-form-' + itemId).style.display = 'none'
        })
    })
}

Answer №2

It's possible that the issue arises because your div event is linked to document.ready, and after a certain amount of time elapses, my_function runs which removes the original item divs from the page without attaching events to the new item divs.

To resolve this, consider binding the div event in the $('#timeline').loaded event instead.

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

Customize blueimp-jQuery-File-Upload to upload files to a specific folder

My current project involves using the blueimp fileupload feature to upload images linked with specific property records. Each property's images are stored in a subdirectory of files that is identified by the record ID, such as files/1/img.jpg. In ord ...

Picking an element that has a dynamic data attribute, but also considering those with a hyphen

Currently, I am developing a function that will select a span element when clicked based on its data attribute and value. Here is the code snippet: function moveFilterElements(event) { if ($(event).hasClass('active')) { var dataAtt ...

What steps should I follow to successfully incorporate Zurb Foundation 4 Sections (tabs) into my Javascript Ajax functionality?

I am currently incorporating Zurb Foundation 4.1.5 into my application and I am faced with the challenge of implementing Zurb Section Javascript to handle "tabs" on the page. The content within these tabs is dynamic and fetched via Ajax calls. I am seeking ...

Combining an AJAX POST within a JSON GET request

function performTest() { $.getJSON("/Home/GetAp", function (result) { $.each(result, function () { if (this.is_disabled == "False") { var a = $("#MainDiv") .append('<div id="imagew ...

Every time I restart the server with MEN stack, I encounter an error message stating "Cannot read property 'name' of null"

I am currently working on developing a campgrounds application based on Colt Steele's Udemy course "The Web Developer Bootcamp". Everything is going smoothly except for one issue I encountered. When I restart the server and directly access the URL wit ...

Creating a unique custom selector with TypeScript that supports both Nodelist and Element types

I am looking to create a custom find selector instead of relying on standard javascript querySelector tags. To achieve this, I have extended the Element type with my own function called addClass(). However, I encountered an issue where querySelectorAll ret ...

Scrapy spider malfunctioning when trying to crawl the homepage

I'm currently using a scrapy scrawler I wrote to collect data from from scrapy.contrib.spiders import CrawlSpider, Rule from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor from scrapy.selector import Selector from .. import items clas ...

Failure to pass a variable declared within a function to another JavaScript file running simultaneously

After combing through numerous posts on Google and Stack Overflow, I am still unable to pinpoint why this particular issue persists. This case involves 2 HTML files and 2 JS files (explanations provided below in text following the code snippets). 1) inde ...

Having difficulty modifying the values of my input types on the edit page

After successfully adding user values from the add user page, I encounter an issue when attempting to edit these values such as firstname and lastname on the edit page. Please review the code snippet below for any possible errors. import React from ' ...

Avoiding Duplicate Paths in URLs with Perl CatalystOne common issue that can occur in web development is the presence of double

I recently developed a web application using Catalyst framework. The login page can be accessed by typing the URL: http://mydomainname/login When accessing this URL, the login page is displayed beautifully with all its styling from the CSS file. However ...

Press a button to activate a function on a dynamically created table using Ajax

On my website, I have an ajax function that dynamically generates a table and displays it inside a designated div. Below is the PHP code called by the Ajax function. echo "<table border='1' cellspacing='12' cellpadding='4' ...

Issue with Django: Unable to fetch data from server response in Ajax

Just starting out with Django and trying to figure out how I can dynamically add content from a python script without reloading the page. In my views.py file, I have two functions - one for uploading a file (home) and another for calling a python script t ...

Unclear outcomes from iterative loops

I have a question about this particular for loop: for (var i=0,j=0;i<4,j<20;i++,j++) { a=i+j; } console.log(a); Can someone explain why the output is 38? I initially expected it to be 6. ...

Ways to retrieve a specific item from a constantly changing knockout observableArray without employing a foreach loop

Why can I only access one property ('member_A') of an Element in an observableArray using an HTML <input>? I am attempting to add a new object of type abc() to the observableArray "list_of_abc" when the button "ADD To List of abc" is click ...

Master Angular Autocompletion

Looking to add a filter autocomplete feature but unsure of how to implement it. Any assistance would be greatly appreciated! I've come across some examples, but they don't quite fit my needs. Here's the snippet of code: <mat-form-field c ...

How can I substitute a specific capture group instead of the entire match using a regular expression?

I'm struggling with the following code snippet: let x = "the *quick* brown fox"; let y = x.replace(/[^\\](\*)(.*)(\*)/g, "<strong>$2</strong>"); console.log(y); This piece of code replaces *quick* with <strong& ...

How about this: "Leveraging the power of #IEroot to achieve a

Has anyone successfully implemented the IE CSS hack #IEroot? I came across it while reading this informative article, but unfortunately, it doesn't seem to be working for me. I'm currently trying to resolve an inline styling bug in order to achi ...

Exploring the Input Items to Extract Minimum and Maximum Values

I am seeking assistance with implementing JQuery Min Max Validation for dynamically created input items in a looping structure. On my PHP page, I have a dynamic table that iterates through data fetched from the database. The number of input items (cells) i ...

Learn how to collapse a collapsible section in Jquery Mobile by clicking on a link. Check out the example on JSFiddle

Is there a way to make the data-role collapsible collapse when clicking a tab link? I've tried using an on-click function without success. Any ideas or alternative solutions? Thanks. Check out my JSFiddle, where you can see that the tabs change but t ...

Displaying Bootstrap star rating twice in a recursive manner

After reading about the issue with Bootstrap star rating displaying twice on Stack Overflow, I found myself facing a similar problem. <div class="row"> <input id="input-id123" type="number" class="" min=0 max=6 data-stars=6 step=1> </di ...