Honzis Novák
Honzis Novák

Reputation: 269

JS: Undo last OnClick evnet

I guess, that this is easy, but I can't figure it out.

I have a series of OnClick buttons (like a tree of choices).

Is there any easy way, how could I undo last click? I want this function to be fixed to only one button (in html). I know, that I can do this with series of many buttons, and in JS I can make them as OnClick, that will have opposite function, than I did in prewious step.

I hope, that I descriped it properly.

I also created a Fiddle: https://jsfiddle.net/sz57cyyf/5/

When you click on button A, then will be buttons AA and AB shown. I want to go step back, so I can click on button BACK. What I want is a function linked to button BACK, that'll automatically do opposite function. And like this when you have buttons ABA, BAA etc. like in browser when you click "Back".

This is for users of my website. They will click on buttons and they will get to thing, that they want. So, you click for example like this: A -> AB -> ABA buttons (you have allways 2 choices). This works for me. But what I want is, that when you accidently click (4 example) on button AB, but you wanted to click on button AA, I want to go back a step. So You can get by pressing ".back" from AAA / AAB buttons to AA / AB buttons and then to A / B buttons.

Upvotes: 3

Views: 1045

Answers (2)

Mohammad
Mohammad

Reputation: 21489

You can use jquery data() method to storing button value in html data-* attribute.

$(".button").click(function(){
    var nextIndex = parseInt($(this).data("button")) + 1;
    $(this).data("button", nextIndex).text("Button-" + nextIndex); 
});

$(".back").click(function(){
    var prevIndex = parseInt($(".button").data("button")) - 1;
    if (prevIndex > 0)
        $(".button").data("button", prevIndex).text("Button-" + prevIndex); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="button" data-button="1">Button-1</button>
<button class="back">Back</button>

Upvotes: 1

asenovm
asenovm

Reputation: 6517

Something like this maybe?

$(".back").click(function () {
    if ($(".c").is(":visible")) {
        $(".c").css("display", "none");
        $(".b").css("display", "block");
    } else if ($(".b").is(":visible")) {
        $(".b").css("display", "none");
        $(".a").css("display", "block");
    }
});

Upvotes: 1

Related Questions