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");
    }
});
\$\endgroup\$
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/

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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