DenyThyNature
DenyThyNature

Reputation: 13

Add fade effect to javascript that shows and hides divs?

I'm currently using this javascript to show one div and hide all of the others. It works great. However, I would like to add in a fade effect when the div shows and when the other's disappear.

var divState = {};
function showhide(id) {
if (document.getElementById) {
    var divid = document.getElementById(id);
    divState[id] = (divState[id]) ? false : true;
    //close others
    for (var div in divState) {
        if (divState[div] && div != id) {
            document.getElementById(div).style.display = 'none';
            divState[div] = false;
        }
    }
    divid.style.display = (divid.style.display == 'block' ? 'none' : 'block');
}
}

Here is the jsfiddle with it in action. http://jsfiddle.net/8e8sH/2/

Any help would be greatly appreciated. Thanks.

Upvotes: 0

Views: 1084

Answers (3)

j08691
j08691

Reputation: 207881

I'd do it like this jsFiddle example

HTML

<a href="#" data-box="box1">Box 1</a> 
<a href="#" data-box="box2">Box 2</a> 
<a href="#" data-box="box3">Box 3</a> 
<a href="#" data-box="box4">Box 4</a>

<div id="hiddendivs">
    <div id="box1" class="box_1">Box 1 Test</div>
    <div id="box2" class="box_2">Box 2 Test</div>
    <div id="box3" class="box_3">Box 3 Test</div>
    <div id="box4" class="box_4">Box 4 Test</div>
</div>

CSS

#hiddendivs > div {
    display:none;
    position:absolute;
}
#hiddendivs {
    position:relative;
}
.box_1 {
    width:200px;
    height:200px;
    font-weight:bold;
    background-color:#FF0000;
    border:1px solid #000000;
}
.box_2 {
    width:200px;
    height:200px;
    font-weight:bold;
    background-color:#6699FF;
    border:1px solid #000000;
}
.box_3 {
    width:200px;
    height:200px;
    font-weight:bold;
    background-color:#FFFF00;
    border:1px solid #000000;
}
.box_4 {
    width:200px;
    height:200px;
    font-weight:bold;
    background-color:#00CC99;
    border:1px solid #000000;
}

jQuery

$('a').click(function (e) {
    e.preventDefault();
    $('#hiddendivs div').not($('#'+$(this).data("box"))).fadeOut();
    $('#' + $(this).data("box")).fadeToggle();
})

And as an aside, the CSS can be streamlined further.

Upvotes: 1

T.J. Crowder
T.J. Crowder

Reputation: 1074138

It's well worth your time reading through the jQuery API documentation. It takes 1-2 hours in total, and pays off huge dividends.

In this case, replace your assignments to style.display with calls to jQuery's fadeIn and fadeOut.

Upvotes: 0

iamdev
iamdev

Reputation: 726

Can you use jquery? If so, it's as easy as

$('#divid1').fadeIn();
$('#divid2').fadeOut();

fadeIn() fadeOut()

And you can include a parameter for how long you'd like to fading to take.

Upvotes: 0

Related Questions