Aisha
Aisha

Reputation: 247

How to run jquery only one time

I would like to know how to run a jquery function only one time when the page is loaded first time. It means when i load the page again jquery function should not run.

example:

$(document).ready(function(){
   $(window).load(function(){
     alert(hello);
 });
});

please help. Thanks in advance

Upvotes: 0

Views: 1488

Answers (2)

Daniel Cheung
Daniel Cheung

Reputation: 4819

super easy HTML5 approach: (not suitable for older browsers)

$(function(){
    if(window.localStorage.getItem("ran") != "true") {
        //your running once code here.
        window.localStorage.setItem("ran", "true");
    }
})

The code code simply try to get the field "ran" via the local storage from HTML5, which is supported by modern browsers.

If you would like to support older browsers, translate this into a cookie format, like this:

$(function(){
    if(document.cookie != "ran=true") {
        //your running once code here.
        document.cookie = "ran=true";
    }
})

Upvotes: 0

atmd
atmd

Reputation: 7490

To do that you'd need to set some storage/persistence

$(document).ready(function(){
    if (!localStorage.getItem('loaded')) {
        alert(hello);
        localStorage.setItem('loaded', 'done');
    }
});

The above checks for a record in localStorage, and sets if not already

One thing to note with both local and session storage is that values are stored as strings, so be careful if setting values to true/false as they wont be Boolean on retrieval.

Upvotes: 4

Related Questions