I have the following code that dynamically creates an environment over a page. The ultimate goal is to create a "walk-through wizard" for users.
This code adds an overlay over my page, and then a container with a next and previous button in it.
Then, using Ajax, I populate the container for each step (triggered by the Next/Prev buttons).
In order to achieve some unique styles and apply unique functions to each step, I add a class to the container and to the buttons for each step. For example, The first step, the container has the class step1, as do the buttons, second step has the class step2 applied to the container and buttons and so on.
What I'm finding is that I can't apply functions to buttons based on the class that changes using jQuery.
For example, here is my code that creates the environment, calls the files for each step and adds all the 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>');
// here's the steps
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));
});
});
Now if I were to add the follownig code to send a message to the console when the button with class .step2 is pressed:
$('.step2 #next').click(function () {
console.log('step 2 pressed');
});
Nothing happens. I think this is because I am changing the class via jQuery, however, I have no idea how to get around this problem.
Here is a jsfiddle showing my issue: https://jsfiddle.net/dkzjpnbo/3/
(Obviously I can't load the files using jsfiddle, but if you inspect the elements, you will see that second time you press NEXT (which has the class step2 it should send an alert, but it does nothing)