\$\begingroup\$
\$\endgroup\$
I've made a simple drawer using CSS3 and jQuery that works with hover and click. It seems to be working fine but surely there's a simpler way of writing the code.
Fiddle: http://jsfiddle.net/73MpU/
$("#bottom-page").click(function () {
$("#top-page").addClass("push");
});
$("#bottom-page").mouseover(function () {
$("#top-page").addClass("nudge-right");
});
$("#bottom-page").mouseleave(function () {
$("#top-page").removeClass("nudge-right");
});
$("#top-page").click(function () {
$(this).removeClass("push");
$(this).removeClass("nudge-left");
});
$("#top-page").mouseover(function () {
if ($(this).hasClass("push")) {
$(this).addClass("nudge-left");
}
});
$("#top-page").mouseleave(function () {
if ($(this).hasClass("push")) {
$(this).removeClass("nudge-left");
}
});
So, I simplified my code a bit. Is this valid?
Edit:
$("#bottom-page").hover(function () {
$("#top-page:not(.push)").toggleClass("nudge-right");
});
$("#bottom-page").click(function () {
$("#top-page:not(.push)").removeClass("nudge-right");
$("#top-page:not(.push)").addClass("push");
});
$("#top-page").hover(function () {
if ($(this).hasClass("push")) {
$(this).toggleClass("nudge-left");
}
});
$("#top-page").click(function () {
if ($(this).hasClass("push")) {
$(this).removeClass("push nudge-left");
}
});
Scott SpeedScott Speed
1 Answer 1
\$\begingroup\$
\$\endgroup\$
You could try to group the toggleClass
inside one .hover
, like this:
var $top=$("#top-page"); //save #top-page in $top var
$("#bottom-page").click(function () {
$top.addClass("push");
}).hover(function(){ //chain .hover to #bottom-page
$top.toggleClass("nudge-right");
if ($top.hasClass("push")) { //if $top has the .push class then toggle .nudge-left
$top.toggleClass("nudge-left");
}
});
$top.click(function () { //on $top click remove the .push and .nudege-left class
$top.removeClass("push nudge-left");
});
Alex L
5,7832 gold badges26 silver badges69 bronze badges
answered May 23, 2014 at 15:10
default