JavaScript codes within HTML elements may not be functional when using an AJAX loader to transition to the next page

I'm experiencing issues with an ajax loader in Wordpress.

The theme I am using has an ajax loader button that is interfering with my inline script.

Despite reading over 10 articles on the problem, I haven't been able to find a solution yet.

Does anyone have any suggestions for resolving this issue?

Here is the javascript code I've been working with:

if (typeof(localStorage) == 'undefined') {
  document.getElementById("warning").innerHTML =
    'Browser not supported Storage...';
} else {
  
$('.item').each(function() {
    var div = $(this).closest(".item").attr("id");
    
    if (localStorage["Catalin-" + div] == 1) {
      $(this).addClass('selected');
    }
    
});


$(document).ready(function() {
  
  
$('.buton').on('click', function() {   
   var div1 = $(this).closest(".item").attr("id");
   var $oku_kontrol = $(this).closest('.item');
   
   $oku_kontrol.toggleClass('selected');
   
   if ($oku_kontrol.hasClass('selected')) {
     localStorage.setItem("Catalin-" + div1, 1);
   }
   else {
     localStorage.setItem("Catalin-" + div1, 0);
   }
     
});   
  
  
});  
  
}  
.item {
    width:200px;
    height:80px;
    border:1px solid red;
}

.selected {
background-color:yellow;
}

.buton:after {
color:white;
display:inline-block;
padding:6px;
background:green;
content:"Click Me!";
}

.selected .buton:after {
background:black;
content:"You already did ;)";
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>


<div id="1" class="item">1<br>
<a class="buton"></a>
</div>

<div id="2" class="item">2<br>
<a class="buton"></a>
</div>

<div id="3" class="item">3<br>
<a class="buton"></a>
</div>


<div id="warning"></div>

This code works across the entire website. However, when the page loads content within the same div using an ajax loader, the code stops functioning without any console errors and the click function ceases to work as well.

Any assistance would be greatly appreciated.

Here is the ajax loader javascript code I am currently using:

$('.pager_load_more').click(function(e){
e.preventDefault();

var el = $(this);
var pager = el.closest('.pager_lm');
var href = el.attr('href');

// index | for many items on the page
var index = $('.lm_wrapper').index(el.closest('.isotope_wrapper').find('.lm_wrapper'));

el.fadeOut(50);
pager.addClass('loading');

$.get( href, function(data){

// content
var content = $('.lm_wrapper:eq('+ index +')', data).wrapInner('').html();

if( $('.lm_wrapper:eq('+ index +')').hasClass('isotope') ){
// isotope
$('.lm_wrapper:eq('+ index +')').append( $(content) ).isotope( 'reloadItems' ).isotope({ sortBy: 'original-order' });
} else {
 
 // default 
 $( content ).hide().appendTo('.lm_wrapper:eq('+ index +')').fadeIn(1000);
 }

// next page link
 href = $( '.pager_load_more:eq('+ index +')', data ).attr('href');
 pager.removeClass('loading');
 if( href ){
 el.fadeIn();
 el.attr( 'href', href );
 }

// refresh some staff -------------------------------

 mfn_greyscale();

 mfn_jPlayer();

 mfn_pretty();

 // isotope fix: second resize

 setTimeout(function(){
 $('.lm_wrapper.isotope').isotope( 'layout');
 },1000);


 });

 });

Answer №1

It seems like the page loader might be affecting the DOM and breaking your jQuery bindings. To handle dynamically loading content, it's best to follow these steps:

  1. Enclose the dynamically loaded content in a container like a div.

    <div id="outerDiv">
        //... content that is reloaded here
    </div>
    
  2. For your jQuery binding, target the outer container using this approach.

    $(document).load(function()
    {
        $('#outerDiv').on('click', '.button', function(e)
        {
            e.preventDefault();//------ add this
            e.stopPropagation();
            // perform your button actions
    
            return false;
        });
    });
    

Here's why this works: If you simply use

$('.buton').on('click', function().....

jQuery attaches a click listener to every element with the class .buton on page load. However, when the page reloads, those elements change. Instead of rebinding everything, bind to a stable element like the outerDiv which remains constant even after dynamic content changes. jQuery can then find the .button elements within it.

EDIT: Anchor tags are causing navigation interruptions, so prevent them using e.preventDefault(). Consider adding e.stopPropagation() if needed, but ensure to include the e parameter in the function definition function(e).

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

Locate a piece of text with jQuery and enclose it within a specified container

Check out this code <form method="get" name="form_delivery"> Pick the country where you want your delivery<br> <select name="deliverymethod"> <option value="0" selected="selected">Choose a country / region</option> ...

Using Angular with OpenStreetMap and $routeProvider allows for dynamic routing and

Check out this awesome single page app that I found: https://github.com/tombatossals/angular-leaflet-directive/blob/master/examples/simple-example.html However, I am looking to enhance it by adding a menu... <html ng-app="App"> <head> <lin ...

To avoid the sudden appearance of a div on the screen, React is programmed to wait for the

Struggling with preventing a flashing div in React where the error message renders first, followed by props, and finally the props render. The EventsView component includes the following code: view.js var view; if (_.size(this.props.events) !== 0) { vie ...

Tracking the progress of jQuery ajax requests

I'm currently using jQuery $.ajax to send files over the internet. Is there a way for me to receive updates on the progress of the file transfer, and then adjust the settings accordingly? Below is my current implementation of $.ajax : $.ajax({ ...

Adjust positioning of navigation when hovered over

Need help creating a cool navigation effect like this. Live example: https://hookandbarrelrestaurant.com/ Here is my code: https://codepen.io/Dhaval182/pen/rQPMoW ...

The act of sending back Null from the Array.map() function

I've been attempting to retrieve data from a JavaScript object using the array.map() function. However, the result I'm receiving is null. I'm confused as to what the issue might be. Here's the object: export const Course = [ { co ...

Can you create asynchronous code or functions without using Web APIs at all?

Even though JavaScript is single-threaded, I can't help but wonder about a function that takes an unusual amount of time without any involvement from web APIs like this: console.log("start") function banana() { let bananaCount = 10; while (b ...

What is the method for transforming an array object into an object?

How can I assign the values of an array object called hello to a constant called answer, changing the key value in the process? I've considered using Object.entries but couldn't quite get it right. Is there a way to achieve this? Here is my cod ...

JavaScript middleware not detected

Currently, I have begun self-learning and encountered a roadblock that I can't seem to overcome. I am attempting to design a login page and delving into middleware for the first time. The error message I'm facing is: throw new TypeError('a ...

Error encountered with CORS in a Socket.io Express HTTP server backend

While developing an app that utilizes express for the backend, I decided to incorporate socket.io for real-time chat functionality. Everything was working flawlessly on postman until my front end react code triggered a cors error when making a GET request ...

Attaching dynamic data to a specific element within an array

I have successfully created a demo where elements can be dropped into a specific area and their top and left values are displayed. I have also added functionality to remove dropped items and move them between different blocks. However, I am encountering so ...

use ajax to post saved data to a WebAPI in php

I have successfully implemented the code to save data in a custom table using Ajax. Now, I need to figure out how to send this data to an asp.Net API using js/jQuery. How can I achieve this? Below is my HTML form and JS code: <div id="inline1" class= ...

I noticed that when I include the www in the URL, I am unable to retrieve the API results. However, when I exclude the

Whenever I try to access my website through www.mywebsite.in, it fails to display my data. However, if I visit the site without the www prefix, everything works fine and I can retrieve data from the database. I'm currently utilizing APIs for both get ...

Uploading images in Laravel through $.ajax: A step-by-step guide

I have been struggling to send image upload via AJAX in Laravel using jQuery. Every time I try, I end up with an empty $_FILES array. I have made sure to include enctype="multipart/form-data" in my form tag. Surprisingly, when I submit the data using the p ...

Development with Node JS, express, Mongoose, and intricate nested queries

I'm struggling with a group of interconnected queries using express/mongoose, structured like this: app.get(..., function(...) { Schema1.query(..., function(..., res1) { for ( var key in res1 ) { Schema2.query(..., function(..., ...

Switching from AngularJS to vanilla JavaScript or integrating AngularJS and Flask on a single server

It is common knowledge that angular has the ability to create a project and convert it into pure HTML, CSS, and js code. Similarly, I am looking to do the same for my AngularJS application. When I execute the app using npm start it works perfectly fine. My ...

Refresh the view seamlessly using Ajax without reloading the page

When a button is clicked, the following code will run: $.ajax({ type: "POST", url: base_url+"/controller/method", data: {val: value}, success: function(data){ data = jQuery.parseJSON(dat ...

Initiate the countdown when the button is pushed

Recently ran into an issue where a button triggers a command to a Perl script, causing the page to continuously load for 60 seconds. To provide users with transparency on when the Perl script will be finished running, I implemented a JavaScript countdown t ...

Removing cookies after sending a beacon during the window unload event in Chrome

Here's the situation: I need to make sure that when the browser is closed or the tab is closed, the following steps are taken: Send a reliable post request to my server every time. After sending the request, delete the cookies using my synchronous fu ...

Provide a boolean value of true or false to indicate whether all delete operations were successfully completed

Currently, I am using Sequelize, GraphQL, and Typescript for my coding. Within my database, I have two tables named RecordInformation and OtherDescription. The RecordInformation table contains a foreign key called "OtherID" which references the OtherDescri ...