Olivera Kovacevic
Olivera Kovacevic

Reputation: 717

Animate element only if position is not 0

I am trying to make ul#pikame move right it its relative position IS 0, but it keeps moving right even if position is not 0.

I know li_left is set to 0 at the beginning, and it remembers that and sticks to it, but I need li_left to update for each new click.

My code:

li_left = $('ul#pikame').css('left');
if (li_left == '0px') {
    $('a.prev').click(function (e) {
        // e.preventDefault();
        $('ul#pikame').animate({
            'left': '+=127'
        });
        e.preventDefault();
    });
}

to sum up, it should move right only ONCE, because after the first click the position left will not be 0.

Upvotes: 0

Views: 39

Answers (2)

gvee
gvee

Reputation: 17161

if (li_left == 0) { ...

If you look at the value returned by $('ul#pikame').css('left'); you will find that it is an integer. You're currently comparing it too a string literal of "0px", which is not equal.

Alternatively, it looks like you're trying to only perform the action once. If this is the case then you can use JQuery's one() function to perform the action - you guessed it - just once!

DEMO: http://jsfiddle.net/P2L5F/

$('div').one('click', function() {
    $(this).animate({
        'left': '+=127'
    });
});

Upvotes: 1

Karl-André Gagnon
Karl-André Gagnon

Reputation: 33870

Your condition should be inside the click handler, not outside.

$('a.prev').click(function (e) {
    li_left = $('ul#pikame').css('left');
    if (li_left == '0px') {
        // e.preventDefault();
        $('ul#pikame').animate({
        'left': '+=127'
    }
    e.preventDefault();
});

Upvotes: 0

Related Questions