Daiaiai Daiaiai - 4 months ago 9
Javascript Question

How can I increase a CSS property's value repeatedly on click?

I want to add (in this case, decrease, technically) the value of an element each time a different element is clicked. What I have so far:

$("#trigger_heritage").click(function () {
$(".heritage_content ul").css("margin-left", + -880);
// So each time clicking shall move the .heritage_content ul-element 880px further left
});


It gets
880px
far left, but only once. What I want is that this value gets increased each time the other element gets clicked.

How would I do that?

Answer

Here is a simple example:

$(document).ready(function() {
    var move = 0;
    $(".left").click(function () {
        move -= 25;
        $(".move").css("margin-left", move + "px");
    });
    $(".right").click(function () {
        move += 25;
        $(".move").css("margin-left", move + "px");
    });
})

Fiddle: https://jsfiddle.net/gjfjahjo/

Comments