4
\$\begingroup\$

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");
 }
});
asked May 11, 2014 at 11:59
\$\endgroup\$

1 Answer 1

1
\$\begingroup\$

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");
}); 

http://jsfiddle.net/73MpU/1/

Alex L
5,7832 gold badges26 silver badges69 bronze badges
answered May 23, 2014 at 15:10
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.