user5308956
user5308956

Reputation:

Hide many divs with on button click

I have 6divs and i want on button click to hide five and show one, on other button click to hide five others and show one. I don't want to hide all them one by one. Is any way to hide all by ID in the same time: My html code:

<div id="ad1" style="display: none;">Div content 1</div>
<div id="ad2" style="display: none;">Div content 2</div>
<div id="ad3" style="display: none;">Div content 3</div>
<div id="ad4" style="display: none;">Div content 4</div>
<div id="ad5" style="display: none;">Div content 5</div>
<br/>
<button id='button1'>click1</button>
<button id='button2'>click2</button>
<button id='button3'>click3</button>
<button id='button4'>click4</button>
<button id='button5'>click5</button>

I tried something like this:

$("#button1").click(function () {
    $("#ad1").show();
    $("#ad2 #ad3 #ad4 #ad5").hide();
});

$("#button2").click(function () {
    $("#ad2").show();
    $("#ad1 #ad3 #ad4 #ad5").hide();
});

My jsfiddle : DEMO

Any help :)

Upvotes: 0

Views: 90

Answers (2)

Mitul
Mitul

Reputation: 3427

$("#button1").click(function () {
    visible =  $(".ads:visible");
    next = visible.next(".ads");
    debugger;
    if(next.length > 0 ){
    	next.show();
    }else{
    $(".ads").first().show();
    }
    visible.hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="ads" id="ad1">Div content 1</div>
<div class="ads" id="ad2" style="display: none;">Div content 2</div>
<div class="ads" id="ad3" style="display: none;">Div content 3</div>
<div class="ads" id="ad4" style="display: none;">Div content 4</div>
<div class="ads" id="ad5" style="display: none;">Div content 5</div>
<br/>
<button id='button1'>click1</button>

Upvotes: 0

Chris
Chris

Reputation: 783

Just separate the elements with , to select multiple elements:

$("#button1").click(function () {
    $("#ad1").show();
    $("#ad2, #ad3, #ad4, #ad5").hide();
});

$("#button2").click(function () {
    $("#ad2").show();
    $("#ad1, #ad3, #ad4, #ad5").hide();
});

Here is your updated FIDDLE

Upvotes: 2

Related Questions