Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

jquery second click no works when add class and remove class

jQuery(document).ready(function() 
{

if(jQuery("#init").hasClass("show_box"))
{
jQuery("#init").click(function() {
jQuery("#box").show(1000);
jQuery("#init").removeClass("show_box");
jQuery("#init").addClass("hide_box");
});
}
}); 



jQuery(document).ready(function() 
{
if(jQuery("#init").hasClass("hide_box"))
{
alert("ok");
jQuery("#box").hide(1000);
}
});
<div id="box" style="position:relative;width:100px;height:100px;background-color:red;display:none";></div>
<span id="init" class="show_box"> Box Action </span>

As you can see the jquery script show div with id box when click over Box Action, also add class and remove class, show_box and hide_box, in this moment in the second step when change class and try click for activate second script part and hide box, no works, in this case i try without click for automatic hide when change class for hide box but continue don´t works.

I see inside DOM and show_class change, and i try all kind of things and don´t works in the second step for hide box when click in Box Action

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

try this answer.

don’t write on click event 2 times for the same div. just write one on click event and on to this function check with if else condition. and add or remove your class.

Also, you can write the same code using toggleClass

jQuery(document).ready(function() {
  jQuery("#init").click(function() {
    if (jQuery("#init").hasClass("show_box")) {
      jQuery("#box").show(1000);
      jQuery("#init").removeClass("show_box");
      jQuery("#init").addClass("hide_box");
    } else if (jQuery("#init").hasClass("hide_box")) {
      alert("ok");
      jQuery("#box").hide(1000);
      jQuery("#init").addClass("show_box");
      jQuery("#init").removeClass("hide_box");
    }
  });
});
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<div id="box" style="position:relative;width:100px;height:100px;background-color:red;display:none;">Test</div>
<span id="init" class="show_box"> Box Action </span>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading