Description: My webpage includes two buttons and two additional elements (div & section). When button 1 is clicked, the div element appears with a HotPink background-color. If button 1 is clicked again, the div element disappears. Similarly, button 2 reveals the section element with a DarkGreen background-color when clicked, and hides it upon a second click.
An added functionality allows both the div and section elements to disappear by clicking on the white space of the body.
Question: How can I create a function that shows the div element when button 1 is clicked, and then hides it when button 2 or any other element on the web page is clicked???
Demo
NOTE: Instead of duplicating code for different classes under separate events, please suggest a more efficient method.
My codes: HTML:
<button class="button1">
Show Div Element
</button>
<div class="div">
I am Div Element
</div>
<br><br>
<button class="button2">
Show Section Element
</button>
<section class="section">
I am Section Element
</section>
JQuery:
$(function(){
$(".button1").click(function(event){
event.stopPropagation();
if($(".div").css("display") == "none"){
$(".div").css("display","block");
}else{
$(".div").css("display","none");
}
});
$(".button2").click(function(event){
event.stopPropagation();
if($(".section").css("display") == "none"){
$(".section").css("display","block");
}else{
$(".section").css("display","none");
}
});
$(document).click(function(){
$(".div").css("display","none");
$(".section").css("display","none");
});
});