Question

$('document').ready(function() {
    $('.button').click(function() {
        $('img').animate({left: "+80px"}, 2000);
    });
});

So, I'm a bit of a newbie to jQuery and stuff. All I want to do is make an image move to the right every time I click a button. When I run it, it works the first time, but when I click the button again, it just stays still.

I was wondering how I could trigger the .click event multiple times.

PS: If it's worth knowing, the button I mention here is actually a <div>. I couldn't get it to work with a <button>.

Was it helpful?

Solution

Try +=:

$('img').animate({left: "+=80px"}, 2000);

OTHER TIPS

try the on event:

var doc = $(document);
doc.ready(function() {
    doc.on('click', '.button', function() {
        var imgElem = $('img');
        var imgLeft = parseInt(imgElem.css('left'));
        var distance = 80;
        var newDistance = imgLeft + distance;
        $('img').animate({left: newDistance+'px'}, 2000);
    });
});

Edit: I changed the code after "remembering" how animate works

$(document).ready(function() {
    $('.button').unbind('click').click(function() {
        $('img').animate({left: "+80px"}, 2000);
        return false;
    });
});

I must works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top