White8Tiger White8Tiger - 3 months ago 8
jQuery Question

jQuery IF not working with position relative + percentage values

I'm really struggling on this one.

I'm trying to create a menu that slides left and right to hide itself, with jquery.

I need to make it

left: 100%
and, on clicking the toggle, make it
left: 0


To do so, I also need it to be
position relative
. But it seems that, if it has
position relative
, the jquery
if
doesn't work.

$('.menu-toggle').click(function(){
if ( $('.menu').css('left') == '100%' ) {
alert('left 100%');
$(this).text('keyboard_arrow_right');
$('.menu').stop().animate({
left: 0
}, 500);
}
else {
alert('left not 100%');
$(this).text('menu');
$('.menu').stop().animate({
left: '100%'
}, 500);
}
});


I made this fiddle to make it easier to test: https://jsfiddle.net/z2cjLrtq/2/

If you try and remove the
position relative
from the fiddle, the code works BUT, then,
left: 100%
won't do a thing since it doesn't have the
position relative


I also tried using
px
instead of
%
and it works as well! But that won't do me any good either since it will be a dynamic menu with fluid width.

I'm starting to think this is a jquery bug...

Is there any solution to this?

I would really appreciate some help.

Thank you in advance

Answer

$('.menu').css('left') returns the actual (calculated) value in pixels, e.g. 0px or 879px, and not 100%.

Therefore all you have to do is reverse your logic, so that you check for the 0px case (when the menu is at the left) instead of trying to work out which pixel value is equivalent to 100%. Something like this:

$('.menu-toggle').click(function(){

        if ( $('.menu').css('left') == '0px' ) {
            $(this).text('menu');
            $('.menu').stop().animate({
                left: '100%'
            }, 500);
        }
        else {
            alert($('.menu').css('left'));
            $(this).text('keyboard_arrow_right');
            $('.menu').stop().animate({
                left: 0
            }, 500);
        }
});