Drazek
Drazek

Reputation: 341

jQuery - go back button or wait and you get auto redirected - advanced go back button

I used this button for a while:

<input type="button" class="button" onclick="javascript:history.go(-1)" value="Go back to previus page" />

And I would like to add feature to it, but I have no clue, since im javascript newb, so please give me some tips or even solution.

I would like that you would get redirected from that page on which this button is located, automaticaly in 10 seconds (timmer should show on the actual button). OR if you click you get redirected instant?

Any ideas how to do this with jquery?

Upvotes: 2

Views: 5028

Answers (2)

Jeff B
Jeff B

Reputation: 30099

No jQuery necessary. Put this in your header. It will call history.go(-1) after 10000 milliseconds, or 10 seconds.

<script type="text/javascript">
      setTimeout( function() {
           history.go(-1);
      }), 10000);
</script>

I just noticed you want a timer on the button. This could use a little jQuery. While you are at it, you should move your inline javascript onclick="javascript:..." to your script body. Inline javascript has fallen out of favor, mostly because it is a lousy way to do things.

<script type="text/javascript">
      $( function() {
             // While you are at it, remove do the click handler here:
             $(document).on('click', '.button', function() {
                 history.go(-1);
             })

             // Get button name, init timer value
             var buttonName = $('.button').val();
             var time = 10;

             function updateButton() {
                  // Set button name to "Go back to previus page (X)"
                  $('.button').val(buttonName+' ('+time+')');

                  if(time <= 0) {
                       // If we reached 0, redirect
                       history.go(-1);
                  } else {
                       //decrement time counter  
                       time--;
                       // otherwise, wait a second and do it again
                       setTimeout(updateButton, 1000);
                  }
             }

             // Start the counter
             updateButton();
      });
</script>

You could use setInterval() also, but this let's you set the button timer at time 0 a little easier.

Example: http://jsfiddle.net/jtbowden/gJsPw/

Upvotes: 7

Mohammed Swillam
Mohammed Swillam

Reputation: 9242

use this

setTimeOut(goBack(),10000);

function goBack()
{
    $(".button").click();
}

Upvotes: 1

Related Questions