I’m trying to do true sliding with jQuery (so the element actually slides up), I came up with the following, i’m not sure it’s very optimised, can you see a way to improve it?
Fiddle at: http://jsfiddle.net/gpuHG/1/
The idea is the .content elements default to being up by their height so they are off the page or behind a header, and when an item on the menu is clicked if any windows are open they close and then the requested item slides down. My solution seems rather bloated for something so simple!
jQuery:
$.fn.exists = function() {
return this.length !== 0;
}
$(".content").each(function() {
$(this).hide().css({
"margin-top": "-=" + $(this).outerHeight() + "px"
});
});
$("#navigation ul li").each(function() {
var relatedContent = $("#" + $(this).attr("title") + "-content");
$(this).click(function() {
if (!$(":animated").exists()) {
if ($(".open").exists()) {
$(".current").first().removeClass("current");
$(this).addClass("current");
var element = $(".open").first();
element.removeClass("open").animate({
"margin-top": "-" + element.outerHeight() + "px"
}, 500, function() {
$(this).hide();
relatedContent.show().addClass("open").animate({
"margin-top": "0px"
}, 500);
});
} else {
$(this).addClass("current");
relatedContent.show().addClass("open").animate({
"margin-top": "0px"
}, 500);
}
}
});
});
Thanks for your time,
Overall, your code is fine, so I didn’t change much. Remember to cache variables as much as possible; DOM access is expensive. Also, providing a context to your selectors will improve performance. There are many more tweaks you could make to this, but here are a few:
EDIT:
I agree with the comment above: your
$.fn.existsfunction is great for convenience, but using.lengthis shorter and faster than hitting an additional function. Keep it if you like, but I’m ditching it in my code.