Is there a more efficient way to do this.( Show Hide Divs / Hide Previously shown Div)?
I am unfortunately not the best Jquery programmer but I thought I would give this a try to see what i could come up with. It works however I don't think it is the best way to accomplish what i am after.
HTML MARKUP:
<ul class="top-menu">
<li><a href="#" class="drop">Sign In</a>
<div id="panel_1" class="panel left">
CONTENT 1
</div>
</li>
<li><a href="#" class="drop">Register</a>
<div id="panel_2" class="panel left">
CONTENT 2
</div>
</li>
JQuery Code:
$(document).ready(function () {
var visId = null;
$(".top-menu li a.drop").click(function () {
var parent = $(this).parent()开发者_如何学编程;
var panel = $(parent).find("div.panel");
if ($(visId) != null && $(visId).is(":visible")) {
if ($(visId).attr("id") != $(panel).attr("id")) {
$(visId).slideUp("fast");
}
}
$(panel).slideDown(function () {
$(this).slideDown();
visId = $(this);
});
});
});
I would do it like so:
Code
$( function()
{
var top_menu = $( 'ul.top-menu' ),
panels = top_menu.find( 'div.panel' );
top_menu.find( 'a.drop' ).click( function( e )
{
var target_panel = $( this ).parent().find( 'div.panel:hidden' );
if( target_panel.length )
{
panels.filter( ':visible' ).slideUp( 'fast' );
target_panel.slideDown();
}
e.preventDefault();
} );
} );
Live Demo:
http://jsfiddle.net/JAAulde/8HZzh/
$(document).ready(function () {
$(".top-menu li a.drop").click(function () {
var panel = $(this).parent().find("div.panel");
$('.top-menu li div.panel').slideUp("fast");
$(panel).slideDown();
});
});
this can help
You bet
http://jsfiddle.net/xPTNS/
.panel
{
display:none;
}
$(document).ready(function () {
$(".panel:first").toggle();
$(".top-menu li a.drop").click(function () {
$(".panel").slideToggle();
});
});
Better solution for multiple items
$(document).ready(function () {
$(".panel:first").show();
$(".top-menu li a.drop").click(function () {
$(".panel").slideUp();
$(this).siblings().slideDown();
});
});
You can try:
$(".top-menu li a.drop").click(function () {
var panel = $(this).next();
if($(panel).not(":visible")){
$(".panel").each(function(){
if($(this).is(":visible"))
$(this).slideUp("slow");
});
$(panel).slideDown("slow");
}
});
Though I feel as if there is a far more efficient way of doing so.
In your code at many places you were wrapping a jQuery object into $()
which is not required because its already a jQuery
object.
$(document).ready(function () {
var visId = null;
$(".top-menu li a.drop").click(function () {
var $this = $(this);
var parent = $this.parent();
var panel = parent.find("div.panel");
$this
.closest('.top-menu')
.find('div.panel:not(#'+$this.next().attr('id')+')')
.slideUp("fast", function(){
panel.slideDown();
});
return false;
}).eq(0).click();
});
精彩评论