Add CSS to specific class after page is already loaded

Viewed 44

I got this multi step contact form and I want to add a class to a specific div depending on which step of the form I am.

The current step is specified with the class ".current". So as you can see, step 1 of my form is currently active (default on page load).

<ul class="multi-step-list">
   <li class="step-1 current">Name</li>
   <li class="step-2">Address</li>
   <li class="step-3">Message</li>
   <li class="step-4">Send</li>
</ul>

Now I have a div where I want to add a class, when step 2 is active with the class ".current" Depending on the step I am, ".current" switches automatically to my current step.

So when step 2 is active, I want to add the class ".myClass" to my div "myDiv".

jQuery(document).ready(function( $ ){
    if($('li.step-2').hasClass('current')) {
        $('div.myDiv').toggleClass('myClass');
    }
});

I know I am wrong here because that would only take effect on page load and step 2 is pre-selected. ".myClass" should only appear when ".step-2" has class ".current" and when I switch to e.g. step 3, the class must disappear.

I hope I can get some advice here.

2 Answers

If you want to toggle the .myClass only when the form changes to a specific step, you should set the .myClass in the same function where you change the form step.

So instead of setting .myClass in $(document).ready() -callback, set it in the function (that you did not include in your question), that is used to switch the form step. And in that function check if the step to switch to is "2", then set .myClass on the div. Otherwise remove the .myClass from the div.

You can call an event on just the one you click, and remove the class from all siblings except the one you're clicking (and add it to that one). And base the same logic to the div you want to change. Like so

$(document).ready(function(){

  $(".step").each(function() {
         $(this).click(function(e) {
     var step2 = 'two';
     $(this).addClass("active-step").siblings().removeClass("active-step");
     if (e.target.id == step2) {
      $(".myDiv").addClass("something");
     } else {
     $(".myDiv").removeClass("something");
     }
    });
});

});
ul {
  padding: 2rem;
}

li {
  padding: .5rem 1rem;
  background: darkorchid;
  list-style: none;
  color: white;
  font-family: sans-serif;
}

li:not(:first-of-type) {
  margin-top: 1rem;
}

.active-step {
  box-shadow: 0px 4px 6px rgba(0,0,0,.6);
  background: teal;
}

.myDiv {
  height: 100px;
  width: 100px;
  background: goldenrod;
}

.something {
  background: royalblue;
  width: 200px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="multi-step-list">
   <li class="step step-1 current">Name</li>
   <li class="step step-2" id="two">Address</li>
   <li class="step step-3">Message</li>
   <li class="step step-4">Send</li>
</ul>

<div class="myDiv"></div>

Related