I have one button. I'm trying to toggle 2 divs with one click. Logic is next:
- On first click hide BOX 1 and display BOX 2
- Second click hide BOX 2 display BOX 1
This is what I tried, but only works on first click, if you uncomment code you will see, not checking visibility of BOX 2
HTML
<a >TOGGLE BUTTON</a>
<div >
<h4>Business Accorodion</h4>
</div>
<div >
<h4>Customer Accorodion</h4>
</div>
JS
jQuery('.toggle-btn').on('click', function(){
checkBusinessVisibility();
// checkCustomerVisibility();
function checkBusinessVisibility() {
if(jQuery(".business-accordion").is(":visible")){
jQuery(".business-accordion").hide();
jQuery(".customer-accordion").show();
}
}
// function checkCustomerVisibility() {
// if(jQuery(".customer-accordion").is(":visible")){
// jQuery(".customer-accordion").hide();
// jQuery(".business-accordion").show();
// }
// }
});
CodePudding user response:
You could do it like this:
jQuery('.toggle-btn').on('click', function() {
checkBusinessVisibility();
});
function checkBusinessVisibility() {
var check = jQuery(".business-accordion").is(":visible");
jQuery(".business-accordion").toggle(!check);
jQuery(".customer-accordion").toggle(check);
}
Like i said in the comment, it's not recommended that you initialize/create a function within a click event or other events like example (change, input) so on .
Demo
jQuery('.toggle-btn').on('click', function() {
checkBusinessVisibility();
});
function checkBusinessVisibility() {
var check = jQuery(".business-accordion").is(":visible");
jQuery(".business-accordion").toggle(!check);
jQuery(".customer-accordion").toggle(check);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a >TOGGLE BUTTON</a>
<div >
<h4>Business Accorodion</h4>
</div>
<div >
<h4>Customer Accorodion</h4>
</div>
CodePudding user response:
jQuery('.toggle-btn').on('click', function(){
checkBusinessVisibility();
});
function checkBusinessVisibility() {
if(jQuery(".business-accordion").is(":visible")){
jQuery(".business-accordion").hide();
jQuery(".customer-accordion").show();
}else{
jQuery(".business-accordion").show();
jQuery(".customer-accordion").hide();
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a >TOGGLE BUTTON</a>
<div >
<h4>Business Accorodion</h4>
</div>
<div style="display:none">
<h4>Customer Accorodion</h4>
</div>