Why is the toggle list not functioning properly following the JSON data load?

I attempted to create a color system management, but as a beginner, I find it quite challenging!

My issue is:

When I load my HTML page, everything works fine. However, when I click on the "li" element to load JSON, all my toggle elements stop working!!! It's strange, could it be a syntax problem?

HTML CODE :

<div id="content">
    <div class="theme-item">
        <ul class="color-list one">
            <li>
                <span class="in"></span>
            </li>
</ul>
</div>


<ul class="elements-list">
    <li class="elements-item">
        <span class="tog">test one</span>
        <div class="togcont hidden">
            <h5 data-title="">text text</h5>
        </div>
    </li>
</ul>
</div>

jQUERY CODE :

$(document).ready(function() {
    // ----------------------
    // JSON INFOS
    // ----------------------   
  $(".color-list li").click(function(event){
    $.getJSON('result.json', function(jd) {
      $('ul.elements-list').html('<li class="elements-item"><span class="tog">' + jd.name + '</span><div class="togcont"><p>Name: ' + jd.name + '</p></div></li>');
      $('ul.elements-list').append('<li class="elements-item"><span class="tog">' + jd.age + '</span><div class="togcont hidden">Name: ' + jd.age + '</div></li>');
      $('ul.elements-list').append('<li class="elements-item"><span class="tog">' + jd.sex + '</span><div class="togcont hidden">Name: ' + jd.sex + '</div></li>');

    });
  });

    // ----------------------
    // TOGGLE BULLZ
    // ----------------------
    $(".tog").click(function(){
        var obj = $(this).next();
            if($(obj).hasClass("hidden")){
                $(obj).removeClass("hidden").slideDown();
                $(this).addClass("bounce");
            } else {
                $(obj).addClass("hidden").slideUp();
                $(this).removeClass("bounce");
        }
    });


});

CSS CODE (PART) :

ul.elements-list {
    list-style-position: inside;
    list-style-type: none;  
}

ul.elements-list li {
    margin: 20px 0;
    background-color:  #393939;
    border-radius: 16px;
    text-transform: uppercase;
    font-weight: 300;   
}

ul.elements-list li .tog {
    color: #FFF;
    cursor:pointer;
    width: 100%;
    display: inline-block;
    box-sizing: border-box;
    cursor:pointer;
}

div.togcont {
    padding:15px 20px;
    overflow:hidden;
    margin-bottom:20px;
    display: none;
    text-transform: none;
    line-height: 1.8em;
    font-size: 1.0em;
    color: #CCC;
    text-shadow: 0 2px 0 rgba(0,0,0,0.3);
}

Answer №1

Consider utilizing event delegation:

$(document).on('click', ".tog", function(){

To ensure that the click handler is triggered for dynamically added elements, delegate the click event using jQuery's .on() method.

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). Therefore, "$(document).on(" is a reliable approach.

Answer №2

Experiment with .on()

$(document).on("click", ".toggle", function(){

Utilize event delegation

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

SyntaxError: End of input caught unexpectedly (NodeJS TCP server)

My simple tcp server has the capability to send and receive json data. Here is a snippet of my code: // Handling incoming messages from clients. socket.on('data', function (data) { var obj = JSON.parse(data); if(obj.type == "regis ...

Interact with Datatable by clicking on the table cell or any links within the cell

When I am working with the datatable, I want to be able to determine whether a click inside the table was made on a link or a cell. <td> Here is some text - <a href="mylink.html">mylink</a> </td> Here is how I initialize my da ...

Remove an item from the DOM instantly with React

Having trouble synchronously removing a child from the container? Here is a simplified code snippet demonstrating the current solution using the useState hook. type ChildProps = { index: number; id: string; remove: (index: number) => void; }; fun ...

Exclude specific outcomes within a nested document in MongoDB

I have a situation where I need to query a list of items and only retrieve the ones that correspond to a specific ID in the provider_cost_dict. Essentially, if I input providerId = 10001, then only the items with a matching entry in the provider_cost_dict ...

Cross-Site Scripting: Building a JavaScript object with the help of PHP's json_encode

Is this code 100% secure against XSS attacks? If not, could you provide an example of a malicious string that could make it vulnerable? <html> <body> <script> <?php $bad = "malicious string. Please provide exampl ...

How to toggle between two background colors in a webpage with the click of a button using JavaScript

I need help with a unique website feature. I want to implement a button that cycles between two different background colors (white and black) as well as changes the font color from black to white, and vice versa. My goal is to create a negative version of ...

Combining href into click events - a step-by-step guide

I have an href link available. '<a href="index.php?imei=' + value['imei'] + '&nama=' + value['nama'] + '" class="summarykapal">Summary</a>' This is the function in question: function retr ...

Develop an Engaging JavaScript Quiz with Elements That are Generated Dynamically

** Need help setting answer values for checkboxes Currently, I have a code that displays (2) questions with (4) possible answers each. Next to each answer is a checkbox with a default value of false. However, I want to link the value of each checkbox to ...

Tips for enhancing contrast in MUI dark theme modals

Currently, I am implementing MUI dark mode for my Next.js application. While the MUI modal functions perfectly in light mode, I am struggling with visibility issues when using it in dark mode. The contrast is not strong enough, making it difficult to disti ...

Click on the button to automatically scroll to a specific component inside the dialog

In my JSF/Primefaces application, I have a page with a long content that can be scrolled, along with a dialog also containing lengthy content that requires scrolling. The dialog includes a button and I am looking to scroll the dialog content to a specific ...

Can you specify the doctype used for XHTML5, which is the XML representation of HTML5?

Which doctype is recommended for XML serialization of HTML5? If I keep the file extension as .html, can I still indicate to the browser that the content is XHTML5? ...

Is there a way to prevent certain words or letters from being exchanged in PHP?

In my PHP project, I am trying to replace text in one textarea and display it in another. While most of the code works fine, there are some parts that are causing issues. Currently, I am using the str_ireplace function with around 60 different words and m ...

Reveal a segment of a picture

Is there a way to display only a section of an image using either jQuery or another JavaScript method? For example: image: [ ] [ -------- ] [ - - ] [ - part - ] [ - - ] [ -------- ] [ ...

`How can I load data into a table using a JSON object returned by Spring MVC and Hibernate-based RESTful web services?`

Looking to populate my JQuery table with JSON objects returned by Spring MVC. Here is the structure of my JSON data: { availDate: 1421508979000 custName: "Navin" custMobile: "8765432468" custEmail: "<a href="/cdn-cgi/l/email-protection" class="__cf_ema ...

Is there someone who can assist me in transferring data from an Axios JSON response to plot points on a line chart using Chart js?

I'm currently in the process of developing a React application that includes a line chart showcasing the timeline of data recordings starting from a specific point in time up to the present day. To achieve this, I am leveraging the Chart.js JavaScript ...

What could be causing the "no such file" error to occur while attempting to use the "mammoth" tool to convert a basic .docx file?

Here is my code snippet. The file contains a basic "hello world" and I have the hello.docx file located in the same directory where I am running this mammoth function. Error message: fatal Error: ENOENT: no such file or directory, open './hello.docx& ...

Ways to widen the header to fit the entire page?

I'm having trouble stretching my header to fill the entire page. I've tried using margin-left and right, but it's not working as expected. My Header CSS: background: green; height: 70px; width: 100%; display: flex; just ...

Are there ways to incorporate extra icons into NavMenu in Blazor 8?

I am exploring ways to incorporate extra icons into the NavMenu.razor component of my Blazor version 8 application. In the earlier version, Blazor 7, there was an iconset setup located in wwwroot/css/, which allowed me to include additional icons simply by ...

Is there a need to remove whitespace for additional characters?

Is there a function available that can trim specified characters or strings? For example: var x = '@@@hello world@@'; console.log(x.trim('@')); // outputs 'hello world' var y = 'hellohellohelloworld'; console.log(y ...

Concealing my menu with overflow-x: hidden on the body is not an option

Despite setting overflow-x: hidden on the body element, I'm still experiencing horizontal scrolling and can't seem to find a solution. I've searched online for solutions without success. That's why I'm reaching out here in hopes o ...