简体   繁体   中英

Toggle 2 div with one onclick

I have 2 divs which i need to toggle them with one button, the first one slide Up and the second one slide down.

HTML dasdasdasdasd

<button>Toggle 'em</button>

JQuery

$( "button" ).click(function() {
  $( "#nav" ).slideUp();
});

Can anybody help me out?

JSFIDDLE

You can use class instead of id and make one div hidden by using display:none;

html:

<div class="nav" style="background:black; width:100%; height:95px">dasdasdasdasd</div>
 <div class="nav" style="background:gray; height:200px;display:none;"></div>

<button>Toggle 'em</button>

jquery

$( "button" ).click(function() {
  $( ".nav" ).toggle( "slow" );
});

Demo

Use a class or then name attribute instead of an id .

HTML

<div class="nav" style="background:black; width:100%; height:95px">dasdasdasdasd</div>
 <div class="nav" style="background:gray; height:200px"></div>

<button>Toggle 'em</button>

JS

$( "button" ).click(function() {
  $( ".nav" ).toggle( "slow" );
});

JSFiddle

PS

Never use the same id for two elements. An id should be unigue.

Duplicate ids are invalid html, you should rather use class instead.

You will also need to hide one element in beginning for toggling.:

$( "button" ).click(function() {
  $( ".nav" ).slideToggle( "slow" );
});

Working Demo

You need to hide one element to toggle them differently

$( "button" ).click(function() {
  $( "#nav1" ).slideToggle( "slow" );
    $( "#nav2" ).slideToggle( "slow" );
});

Demo

It seems that your div has an id of nav . In order to select 2 divs, you can try assigning the same class name to both, for example: <div class="nav"></div> (x2)

Then change your jQuery to: $('.nav').slideUp();

That way, jQuery knows to select both divs and slide them up.

Try this,

Html

<div id="nav1" style="background:black; width:100%; height:95px">dasdasdasdasd</div>
<div id="nav2" style="background:gray; height:200px"></div>

And some CSS

#nav1{
    display:none;
}

Script

$( "button" ).click(function() {
  $( "#nav1,#nav2" ).slideToggle( "slow" );
});

Demo

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM