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

utilizing props to create a navigational link

How can I display a tsx component on a new tab and pass props into the new page? Essentially, I'm looking for the equivalent of this Flutter code: Navigator.push( context, MaterialPageRoute(builder: (context) => Page({title: example, desc: ...

The eel feature results in no output

During my Python program development using the Eel module, I encountered an issue. The problem is that the eel.getImgSrc(path) function returns null when trying to retrieve image's byte data. Take a look at this example: -----web/main.js------ async ...

JavaScript regex for the 'hh:mm tt' time format

I need to validate time in the format 'hh:mm tt'. Here is an example of what needs to be matched: 01:00 am 01:10 Pm 02:20 PM This is what I have tried so far: /^\d{2}:\d{2}:\s[a-z]$/.test('02:02 am') ...

Utilize jQuery ajax to target a particular recurring input

I am using HTML code along with another jQuery loop. Within this loop, there is an input element that is also being looped. I am trying to manipulate it using jQuery Ajax... but I am facing an issue where only the first input element works properly. The re ...

In Vue, it is not accurate to measure overflow

I am working on creating an overflow effect with tagging that fades out at the beginning to provide a subtle hint to users that there is more content. Here is what it currently looks like: https://i.stack.imgur.com/fXGBR.png To achieve this, I added a fa ...

What is the most effective way to create a live preview using AngularJS and CSS?

Is there a way to dynamically change the background color of the body based on the hexadecimal value entered in a textfield, without using jQuery? I want the change to happen live as the user types. The current code works but it doesn't feel right. I ...

Reducing image file sizes in Ionic 3

I have been struggling to compress an image client-side using Ionic 3 for the past couple of days. I have experimented with: ng2-img-max - encountered an error when utilizing the blue-imp-canvas-to-blob canvas.toBlob() method (which is a dependency of ng2 ...

Exploring the JSON Structure in NodeJS

My current json array is structured in the following way: [{"id": 1, "meeting": "1/3/2015 12:30:00 PM", "name": "John"}, {"id": 1, "meeting": "1/3/2015 13:30:00 PM"}, "name": "John"}, {"id": 2, "meeting": "1/5/2015 7:00:00 AM"}, "name": "Peter"}, {"id": 2 ...

Performing simultaneous document queries within a single API in MongoDB

I am currently working with an API written in typescript and attempting to execute parallel queries for the same document by using Promise.allSettled. However, I have noticed that it is performing poorly and seems to be running sequentially instead of in p ...

Data-api configuration for bootgrid ajax

According to the BootGrid documentation, in order to set the HTTP method to GET or enable AJAX, one must use the method and ajax attributes in JavaScript. However, the Data-API example demonstrates the use of data-url and data-ajax, leading me to conclude ...

What is the best way to pass a function along with its state to utilize useContext in React

Currently attempting to grasp the concept of using react hooks. I have implemented createContext and am looking to pass both state and a function to other components, but could use some guidance on how to achieve this. I'm also questioning if it is ev ...

JSON containing attributes represented by Unicode characters

During the development of my web application, I am interested in utilizing JSON objects with Unicode attributes as shown below: a = { ονομα:"hello" } Subsequently, I would like to access it in this manner: a.ονομα Alternatively, exploring lo ...

Warning: Update state in React-router-redux after redirection

I am currently developing an admin app for a project using react, redux, react-router, and react-router-redux. The version of react-router I am working with is v4.0.0, while react-router-redux is at v5.0.0-alpha.3 (installed with npm install react-router-r ...

Issue with displaying response content within a div using Ajax

I am encountering an issue when trying to display the value of an AJAX response inside a div. The problem occurs after I receive the response, as it shows in the div for just a split second before automatically hiding. Even after changing the ID to a class ...

Transform a REACT js Component into an HTML document

I'm working with a static React component that displays information from a database. My goal is to implement a function that enables users to download the React component as an HTML file when they click on a button. In essence, I want to give users ...

Karma Test Requirement: make sure to incorporate either "BrowserAnimationsModule" or "NoopAnimationsModule" when using the synthetic property @transitionMessages within your application

TEST FILE import { async, ComponentFixture, TestBed } from '@angular/core/testing'; import { BrowserAnimationsModule } from '@angular/platform- browser/animations'; import { ManagePageComponent } from './manage-page.component& ...

Ways to dynamically insert a new row into a table based on user input in a Postman-like reactive table

Is there a way to dynamically insert a row when a single character is entered into an input field in the header tab, similar to how Postman functions? 1) If a user types any single character in the td of the first row, then a new row should be added below ...

Setting up NextJS on Vercel for website deployment can encounter a common error known as ENOENT Error, which is caused by the absence of a specific file or

Everything works perfectly on my local machine: import fs from 'fs' import path from 'path' export default function createNewDirectory (tokenSignature: string) { const directoryPath = path.join(process.cwd(), 'notes', to ...

Learn how to generate a dynamic pie chart in PHP that can adjust its sections based on the user's input, giving you a fully customizable data visualization tool

let userData = [ { label: "History", data: 90 }, { label: "Science", data: 85 }, { label: "Art", data: 95 }, ]; I have written this javascript code to represent the user's data, but I want it to be more flexible an ...

Cannot find the appended element in an AJAX call using jQuery

Within the code snippet, .moneychoose is described as the div in moneychoose.jsp. Interestingly, $(".moneychoose") cannot be selected within the ajax call. $("input[name='money']").on("click", function() { if ($("#money").find(".moneychoose" ...