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
>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>