Trouble connecting an event to a dynamically added button using jQuery

I am currently working on a project that involves creating a dynamic walk-through wizard for users. The code I have developed adds an overlay to the page and generates a container with next and previous buttons.

By utilizing Ajax, I populate the container with content for each step as users navigate through the wizard by clicking the Next/Prev buttons.

In order to customize the styles and functionality for each step, I apply unique classes to the container and buttons. For instance, the first step is associated with the class "step1" while subsequent steps follow suit with "step2," "step3," and so forth.

The challenge arises when attempting to apply functions to buttons based on dynamically changing classes using jQuery.

Here is an excerpt of the code I've implemented to set up the environment, load files for each step, and assign classes:

jQuery(function ($) {
  $('body').attr('onboarding_step', 'step1');
  $('body.wp-customizer').addClass('skizzar_onboarding');
  $('<div id="so_overlay"></div>').insertBefore('body.wp-customizer');

// First Step
  $('#so_overlay').html('<div id="onboarding_steps_container" class="step1"></div>');
  $('#onboarding_steps_container').html('<div class="onboarding_steps"></div><div class="button_holder"><button id="prev" class="step1"><i class="fa fa-chevron-left"></i> PREV</button><button id="next" class="step1">NEXT <i class="fa fa-chevron-right"></i></button></div>');

// Steps Array
var steps = [
  "wp-content/plugins/skizzar-onboarding/ajax/step1.php",
  "wp-content/plugins/skizzar-onboarding/ajax/step2.php",
  "wp-content/plugins/skizzar-onboarding/ajax/step3.php",
  "wp-content/plugins/skizzar-onboarding/ajax/step4.php",
  "wp-content/plugins/skizzar-onboarding/ajax/step5.php",
];
counter = 0;
$('.onboarding_steps').load(steps[counter]);

$('#next').click(function () {
  counter = (counter + 1) % steps.length; 
  $('.onboarding_steps').load(steps[counter]); 
  $('#onboarding_steps_container, .button_holder button, #so_overlay').attr('class', 'step' + (counter + 1)); 
  $('body').attr('onboarding_step', 'step' + (counter + 1)); 
});

$('#prev').click(function () {
  counter = (counter - 1) % steps.length; 
  $('.onboarding_steps').load(steps[counter]); 
  $('#onboarding_steps_container, .button_holder button, #so_overlay').attr('class', 'step' + (counter + 1)); 
  $('body').attr('onboarding_step', 'step' + (counter + 1)); 
});

});

Despite my efforts, encountering an issue when trying to trigger an action upon clicking a button with a specific class using jQuery. Here's an example:

$('.step2 #next').click(function () {
    console.log('step 2 pressed');
});

Unfortunately, nothing happens in this scenario. It seems that the problem stems from the class changes made via jQuery, but a solution eludes me at the moment.

If you wish to explore the issue further, feel free to visit the following jsfiddle link: https://jsfiddle.net/dkzjpnbo/3/

(Please note that since jsfiddle cannot load files, you may inspect the elements to see that upon clicking NEXT with the "step2" class, it should trigger an alert, yet no response occurs.)

Answer №1

The reason for this issue is that when you add an event in the following way:

$('.step2 #next').click(function () {
    console.log('step 2 pressed');
});

Your code will not be able to handle dynamically added content. Any changes in classes, addition of new tags with that class, or similar modifications will not trigger the event. However, you can avoid this problem by using the $("#next") selector since IDs should always be unique.

An effective solution is to use the on method to add the event over a wrapper container. For instance, start by creating a div like

<div id='wrapper'></div>
at the beginning and then append content to it using jQuery.

$('#wrapper').on("click", ".step2 #next", function () {
    console.log('step 2 pressed');
});

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

What could be the reason for the jQuery/JavaScript code being overlooked?

Currently working on coding an instant chatbox using jQuery that will display the latest chat on top (refreshing when the user sends data via a POST request) and push the oldest chat downward while removing it. The issue arises when more than one latest c ...

Does Node.js offer a solution or module for converting Google Map polylines into a PNG image without the need for rendering HTML?

I'm attempting to generate a PNG image of polylines on a Google Map using Node.js on the backend without utilizing any view engine. I attempted to use the "webshot" Node.js package, but it was unable to save the polylines on the Google Map. app.get( ...

Issues with Image Placement in Internet Explorer

My cat image on my website appears significantly lower than all the other images when viewed on Internet Explorer (v11). While it looks perfect in Chrome, I cannot figure out why this discrepancy exists. For the development of this website, I utilized pred ...

Place a <div></div> element within a collapsible accordion container that conceals the content inside the <div>

My accordion is expanding, but the div inside it appears blank instead of displaying its content. Any suggestions on how to fix this? Thank you. How can I ensure that the div inside the accordion shows its content? Here is the code: http://jsfiddle.net/6 ...

When aot is enabled, ngClass and ngIf condition may not compile successfully

I am encountering an issue with a div using ngClass and ngIf conditions: <div [ngClass]="{ 'active': nbActive === 1 }" > <!-- some stuff --> </div> There is also a similar div using a ngIf condition: <div *ngIf="nbActi ...

Enhance Three.js 3D model visuals with textured surfaces using Fabric.js canvas as a dynamic texture

Exploring the world of Three.js for the first time, I am embarking on a project that involves leveraging a pre-existing 3D model and altering one of its materials to utilize a Fabric.js canvas as its texture. However, I've hit a roadblock where the te ...

Ways to monitor and measure clicks effectively

Within my website, I have a table element with one column and numerous rows. Each row serves as a hyperlink to an external shared drive. <tr><td ><a href="file://xxx">Staff1</a></td></tr> <tr ><td ><a h ...

iPhone screen rotation settings

I'm currently developing an iOS application using PhoneGap and jQuery Mobile. I am looking to restrict the screen orientation to landscape on one specific page, while keeping the other pages in portrait orientation. I have come across a plugin that ca ...

retrieve the data within a specific tag

Can someone help me with the following HTML structure: <div class="dk_options"> <ul class="dk_options_inner"> <li class="dk_option_current"><a data-dk-dropdown-value="">Select State</a></li> <li class= ...

Attempting to store a specific h1 text.event as a variable, allowing it to be saved upon input of the initial letter

After typing the second key, you can continue to input more characters as desired. It is possible to customize the text displayed in the h1 using your own name or any other text of your preference without needing a textbox. $(document).keypress(functio ...

Transforming fonts into various web-compatible font formats

This morning, I delved into the fascinating world of fonts as I am in need of a specific font for my CSS project. It appears to be quite complex to rely on others for correct font types, so I started exploring methods to convert fonts from one type to ano ...

Breaking down the text field into two distinct fields

I have successfully modified the code below to meet a new requirement. The current functionality involves splitting the Price field into Pounds and Pence based on the index of the . symbol. However, I now need to extend this functionality to split a Name ...

Struggling with XML parsing using JQuery

Currently, I am tackling a project that involves creating an endless scroller designed to fetch information from a MySQL database that has been established. As far as my scroller component goes, everything appears to be functioning correctly. Additionally, ...

The functionality of the tree grid bootstrap is not functioning properly when it is dynamically generated, but it works seamlessly when implemented statically

The code below functions correctly and provides the expected output. <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="TreeView_Table_Project.WebForm1" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/ ...

Resizing Images in a Responsive Design

When creating a website, have you considered options besides resizing images for mobile devices? Instead of downloading the full image and resizing it to fit the screen, causing strain on CPU and RAM, are there alternative methods that could be more effi ...

Guide on redirecting a URL with AJAX in just 5 seconds!

How can I achieve a redirect to a specific URL after a successful sign-up using AJAX without losing the response from the AJAX call? Below is the code snippet I am currently working with: sign-up.php if ( $stmt->execute() ) { $response['status&ap ...

Seeking assistance in incorporating an image into a drop-down menu

I am in the process of integrating a CSS based drop-down menu into my Wordpress website, and I need assistance with adding an image on the right side of my links when a user hovers over them in the menu. Below is the code I currently have, along with a ref ...

Is it possible to utilize custom CSS to conceal commas and evade a JSX bug?

One element of my website relies on the following .js code snippet: items.add( `field-${field.id()}`, <div className="Mason-Field Form-group"> <label> {field.icon() ? <>{icon(field.icon())} & ...

drawImage - Maintain scale while resizing

I am currently working on resizing an image using drawImage while maintaining the scale. Here is what I have so far... window.onload = function() { var c = document.getElementById("myCanvas"); var ctx = c.getContext(" ...

unable to update the table due to issues with the knockout observableArray

My goal is to collect values from form fields and store them as an object in an observableArray. I want to display these objects in a table so that every time I hit the 'add' button, the table should be updated. However, I am facing issues with t ...