简体   繁体   中英

Display one div at a time with multiple buttons

Using Foundation 6 as my framework, I wanted to implement a fading effect between two divs when a button is pressed.

The effect I'm trying to do is when button1 is clicked, div2 will hide and fade out (if visible) and div1 will show and fade in, and vice versa.

Here is my Javascript code:

var $button1 = $('#button1');
var $button2 = $('#button2');

var $div1 = $('#div1');
var $div2 = $('#div2');

$button1.click(function() {
  if ($div2.is(':visible')) {
    MotionUI.animateOut($div2, 'fadeOut');
    MotionUI.animateIn($div1, 'fadeIn');
  }
  else {
    $div1.show();
  }
});

$button2.click(function() {
  if ($div1.is(':visible')) {
    MotionUI.animateOut($div1, 'fadeOut');
    MotionUI.animateIn($div2, 'fadeIn');
  }
  else {
    $div2.show();
  }
});

I have gotten div1 and div2 to fade in/out between the two with one button, but I can't seem to get it to work when using multiple buttons.

Here's a really simple way to toggle display:none using jQuery's toggle() methods. I used fadeToggle since you mentioned wanting a fade, but you could use toggle and set a css3 transition instead.

Keeping the code super simple - to match what you have - this is how you would do it: Fiddle: https://jsfiddle.net/f1dshffs/2/

var $button1 = $('#button1');
var $button2 = $('#button2');

var $div1 = $('#div1');
var $div2 = $('#div2');


var toggleDivs = function(){
    $div1.fadeToggle();
    $div2.fadeToggle();
};

$button1.click(toggleDivs);
$button2.click(toggleDivs);

Now there's some things you could do to optimize your code a little bit by selecting by a class instead of an id, and then adding only 1 event to the array of objects.

It reduces the code down to: Fiddle: https://jsfiddle.net/f1dshffs/3/

var buttons = $('.button');
var divs = $('.div');

var toggleDivs = function(){
    divs.fadeToggle();
};

buttons.click(toggleDivs);

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