DON TOLIVER
DON TOLIVER

Reputation: 475

Trigger a jQuery function only once?

I'd like to trigger a jQuery function only once.

For example, if a user loads the page, the jQuery will get triggered. And that's it. It shouldn't trigger on reload or something. It should get triggered only once.

Is this possible? If so, how?

Upvotes: 1

Views: 869

Answers (2)

Zafar Ahmad
Zafar Ahmad

Reputation: 428

Try this code:

<script type="text/javascript">
var trigger_flag = localStorage.getItem('trigger_flag');

if( !trigger_flag ) {
// invoke your function here
localStorage.setItem('trigger_flag', 'flag_is_set');
}
</script>

I have made use of JS localStorgae to set a flag once the method is invoked and it will not be invoked again until the flag is set in localStorage

Upvotes: 3

Amir Popovich
Amir Popovich

Reputation: 29836

One good way to do something (weird) like this is if you generate your html pages using a server side template engine then simply add the script to the page when you want to.

On the client side there are a couple of ways to do something like this, but it will never be a 100%:

  1. passing a param in the url which indicates if you need to run the script or not and after running you run the script you will need to change the url. The problem with this is that when you change the url you reload the page, and the user can always change the query string.

  2. use cookies\localstorage for that - They can be deleted and that's a problem.

Upvotes: 1

Related Questions