Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

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");
    }
});
share|improve this question

1 Answer 1

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/

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.