Ian Vink
Ian Vink

Reputation: 68750

jQuery Back Button OnLond event?

The HTML page needs to modify itself if the user presses the browser back button to see it again after leaving the page.

Using jQuery, how do I get this event?. I've tried this:

    $(function() {
        DoSOmething();
    });

Upvotes: 0

Views: 571

Answers (3)

Owen C. Jones
Owen C. Jones

Reputation: 1495

One possible way would be to detect the user returning to your page, by setting a cookie. It wouldn't be detecting the back button literally, but it would allow you to execute code on return to the page, including if the back button was used.

You can set the cookie with a low lifetime, so it wouldn't hang around long.

It's not necessarily the best way, but it is one possibility. The History API deliberately won't reveal what is in it, for privacy reasons.

Upvotes: 0

ever_x
ever_x

Reputation: 11

Try this website here: http://www.bajb.net/2010/02/browser-back-button-detection/ This has a demo of very simple code using their class which goes:

<script type="text/javascript">
bajb_backdetect.OnBack = function()
{
alert('You clicked it!');//Do something!
}
</script>

This should be able to do the job!

Upvotes: 1

Sam Ccp
Sam Ccp

Reputation: 1162

mmm.. i don't get what you're trying to do, but if you need to execute a function right after the page has been loaded you need to use the load event, such as:

$(window).load(function(){  //all of the code inside this function will fire after the page has been loaded
    DoSomething();
});

the difference with

$(document).ready(function({ //this code will fire as soon as the browser downloads the js file or if it's already on cache, will fire it right after the "handshake" with the server
    DoSomething();
})

is that $(window).load will not fire until all of the communications with the server has been fully resolved and all the HTML is loaded on the browser, while $(document).ready will fire right away.

Maybe your function is looking for elements that are not yet loaded on the page, thus, it doesn't do anything.

If you want, you can do it jqueryless or normal javascript with:

window.onload = function(){
    DoSomething();
}

It's the same as $(window).load but without the jquery's bloat. Hope it helps, cheers.

Upvotes: 0

Related Questions