user998266
user998266

Reputation: 75

Javascript- Using CSS opacity information

I'm puzzled about getting a simple toggle to work that should be fairly simple. I want the div to fade out when the opacity is 100 and fade in when it is 0. http://jsfiddle.net/mGdcm/8/

Javascript-

$('#toggleButton').click(function() {
if ($('#toggleSection').css("opacity") === 0) {
    $('#toggleSection').fadeIn("slow");
}
else {
    $('#toggleSection').fadeOut("slow");
}
return false;
});

HTML-

<a href="#" id="toggleButton">toggle</a>
    <div id="toggleSection" style="opacity:0;"> <p>Why isn't this working?</p></div>

Upvotes: 2

Views: 433

Answers (4)

Joe
Joe

Reputation: 82604

You need to use jQuery, and the correct code using visible selector:

$('#toggleButton').click(function() {
    if ($('#toggleSection:visible').length < 1) {
        $('#toggleSection').fadeIn("slow");
    }
    else {
        $('#toggleSection').fadeOut("slow");
    }
    return false;
});

Example


Example starting with not visible

Upvotes: 1

Will
Will

Reputation: 20235

You can just use the jQuery fadeToggle function.

$('#toggleButton').click(function() {
    $("#toggleSection").fadeToggle("slow");
});

http://jsfiddle.net/mGdcm/16/

Upvotes: 2

Moe Sweet
Moe Sweet

Reputation: 3721

Not a very good solution but it works :)

$('#toggleButton').click(function() {
    console.log($('#toggleSection').css("opacity"));
    if ($('#toggleSection').css("opacity") == 0) {
        $('#toggleSection').fadeIn("slow", function(){
            $('#toggleSection').css("opacity", 1);
        });
    }
    else {
        $('#toggleSection').fadeOut("slow", function(){
            $('#toggleSection').css("opacity", 0);
        });
    }
    return false;
});

Upvotes: 0

Ray Toal
Ray Toal

Reputation: 88378

You need to set jQuery in your fiddle, not MooTools. :)

Also for fading back in, check that the css display property is equal to "none".

Fixed version for you at http://jsfiddle.net/mGdcm/14/.

Upvotes: 1

Related Questions