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

"Enhance your web app with Emotion.js and Preact SSR, complete with

In my preact SSR application, I have utilized Emotion JS 10 for styling purposes. My goal was to incorporate RTL support into the app. To achieve this, I implemented createEmotion and createEmotionServer, leveraging the resulting renderStylesToString to r ...

Retrieve a different action instance variable within the view

In the scenario where I have a View called home.html.erb and the corresponding controller shown below: class StaticController < ApplicationController def home @people = Person.all end def filter @people = .... end def contact end ...

The visibility of buttons can be controlled based on the selected radio option

I have just completed setting up 4 buttons (add, edit, delete, cancel) and a table that displays data received via ajax. Each row in the table contains a radio button identified by the name "myRadio". When a radio button is clicked, I need the buttons to ...

I want to locate every child that appears after the <body> element, and extract the HTML of the element containing a specific class within it

It may sound a bit confusing at first, but essentially I have some dynamically generated HTML that resembles the following: <body> <div class="component" id="465a496s5498"> <div class="a-container"> <div class="random-div"> ...

What are alternative methods for implementing autocomplete search for usernames from a database without relying on jQuery?

Searching through various exam resources, I have come across autocomplete solutions using jQuery. In my MySQL database, I have a collection of usernames. My objective is to create an autocomplete feature which pulls data from the database by utilizing PHP ...

Which is more effective: coding with just plain JavaScript and CSS, or utilizing frameworks?

As a student, is it more beneficial to focus on utilizing pure JavaScript & CSS or frameworks? And which approach is best suited for the professional field? ...

What is the best way to locate the closest element using JavaScript?

Is there a way to locate the closest object to the mouse pointer on a webpage? I have a hypothesis that involves utilizing the array function, however, I am uncertain if that is the correct approach. Furthermore, I lack knowledge of which specific proper ...

Switch up the Angular base URL using ngx-translate

I successfully integrated ngx-translate into my Angular project. Now, I want to dynamically change the base href based on the language selected from the header menu. Currently, the URL appears as: "localhost:4200". However, upon launching the project, it ...

block height has become a constant challenge for me - despite my various attempts, I still cannot seem

Struggling with adjusting the height of my posts. Any help would be appreciated! For more details, please visit: <li> <div class="thumb-img"> <a title="Hiring a Professional Designer for Your Kitchen" href="http://www.mulberrydesignerkitc ...

Navigating with Express 4

Currently, I am in the process of implementing Passport for user signup by referring to this helpful guide: https://scotch.io/tutorials/easy-node-authentication-setup-and-local Overall, everything is functioning properly except for one issue - after a su ...

Transforming retrieved data into an array using Node.js

Got some data from a URL that looks like this: data=%5B1%2C2%2C3%2C4%2C0%5D which when decoded is [1,2,3,4,0]. Used the snippet below to parse the data: var queryObj = querystring.parse( theUrl.query ); Seems like it's not an array. How can I con ...

Are you searching for a stylish tabbed navigation menu design?

I am searching for a tabbed navigation menu specifically designed to showcase images as the tab items. Here is an example of what I have in mind: <div class="menu"> <a href="#"> <img src="images/Chrysanth ...

css overflowing content can disrupt the layout of the screen

I am currently working on creating a modal that will be displayed in the center of the screen with the same width as the main page. However, I am facing an issue where the modal is not perfectly centered. I suspect that this is due to the overflow style ...

"Utilizing jQuery to generate select boxes with the ability to include multiple selection options

Welcome! I have posted some HTML and jQuery code that uses JQuery 1.9.1. CODE SNIPPET $(document).ready(function () { $('#search').keyup(function () { var search = $('#search').val(); if (search.length > 2) { ...

Looking for Angular 2 material components for dart with CSS styling? Need help centering a glyph on your page?

HTML: <div class="border"> <glyph class="center" [icon]="'star'" ></glyph> <div class="centerText"> This Is Text that is centered. </div> </div> Css: .centerText{ text-align: center ...

Ways to implement schema.org and JSON-LD for data labeling on a homepage of a website

After reading extensively on utilizing schema.org to mark structured data, I have a couple of questions. Firstly, is it advisable to use json-ld considering that it's relatively new and not fully supported yet? Secondly, how can I implement schema.org ...

Can a new frame be created below an already existing frame in HTML?

My main.html file looks like this: ----- main.html---------------- <title>UniqueTrail</title> <script src="main.js"></script> <frameset rows='200,200'> <frame id='one' src="f ...

What steps can I take to address the issue of missing @angular/Core modules?

I am encountering an issue with running my Angular 2 project. Here's what I have tried: - Attempted to run the project using npm install and npm start, but it did not work - Cloned a quickstart from Github and replaced it with my src folder, only to ...

Difficulty adjusting image size in "layouts with overflowing images on cards."

I have encountered an issue with resizing images on my browser using a card-based layout that I found on codepen. The strange thing is, the image resizing works perfectly fine on codepen itself, but when I try to implement the same HTML and stylesheet on m ...

Issues arise when the condition fails to function correctly during the process of form

I am currently working on a question from my elder brother's question paper, but I am struggling to solve it. The task is to create a form with two text fields, a radio button, and a submit button. The text fields should be named "account number" and ...