开发者

javascript onclick fade div in (short code)

i'm been lookin all over the place and cannot find exactly what im after anywhere.

the html structure is basically.

<ul&开发者_JAVA百科gt; 
   <li><a href="">link</a></li>
   <div id="us">hidden info</div>
</ul>

the css structure is.

#us {display:none}

I'd like it so when "link" is clicked the div "us" is changed from dipslay:none; to display:block, in a graceful fade in as little lines of code as possible, and then again when the link is clicked its toggled back to display:hidden.

I'm aware that there are lots of things that can do this, but im really lookin for that simplicity in code.

thanks for your time x


You can just use .toggle() with a duration (works in all jQuery versions), like this:

$("ul li a").click(function() { $("#us").toggle("fast"); });

Or, if you're on jQuery 1.4.4+, use .fadeToggle() like this:

$("ul li a").click(function() { $("#us").fadeToggle(); });

Note though, a <div> isn't a valid child of <ul>, so it may render unexpectedly in several browsers...it'd be better to use proper markup.


Something like this:

$("#idfortheanchor").bind("click", function() {
    if ($("#us").is(":visible")) {
        $("#us").hide();
    } else {
        $("#us").show();
    }
});


As there is no fade-toggle in the jQuery core, I'd use:

$('a').toggle(
    function() { $('#us').fadeIn(); },
    function() { $('#us').fadeOut(); }
);


If jQuery UI is an option for you, I can only recommend it. jQuery UI extends jQuery with many nice effects:

show( effect, [options], [speed], [callback] )

But check out the website itself: http://jqueryui.com/demos/show/


thank you everybody for your input! You've been very helpful! The final snippet I've used which i deemed most appropriate was from Nick.

$("ul li a").click(function() { $(this).parent().next().toggle("fast"); });

so thanks again everybody! and hope someone else can find this useful! x

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜