Linda
Linda

Reputation: 143

How to get a javascript function to execute only once on dom ready

I'm getting alerted "hi" over and over again, how do I get it to do it once and stop:

function doSomething() {
   alert('hi');
}

$(function() {
    doSomething();
});

Upvotes: 11

Views: 25638

Answers (7)

spam filter
spam filter

Reputation: 49

The best way is ... with using cookie - like this:

$(document).ready(function () {
    if ($.cookie("blocker") == 1) {
        //your code or without code;
        return;
    } else {
        //your code for first time
        $.cookie("blocker", 1, {
            expires: 1 / 24 / 60 //time, this is one minut
        });
    }
}); 

This code is good if you have smarty on your page

Upvotes: 1

        // Fired once when document is ready
        $(document).one('ready', function () {
              doSomething();
        });

Using .one ensures this is done only once and not repeatedly.It is okay to put several document.ready event listeners (if you need other events to execute multiple times) as long as you do not overdo it, for the sake of readability.

.one is especially useful when you want the alert to appear the first time a web page is opened or when a mobile application is installed the first time.

Upvotes: 17

romaninsh
romaninsh

Reputation: 10664

I think you include your JS file multiple times from the HTML. Clean up your HTML.


Using:

$(function(){
});

is perfectly normal. Using more verbose form have no benefit. If you are writing a plugin, you might want to do this:

function($){
    // $ always refers to jQuery here
    ...        

}(jQuery);
// $ might not be defined here in compatibility mode.

Upvotes: 3

Sam Dutton
Sam Dutton

Reputation: 15269

You might want to stick to the more verbose style:

function doSomething() {
   alert('hi');
}

$(document).ready(function() {
    doSomething();
});

Upvotes: 0

James Johnson
James Johnson

Reputation: 46047

Are you looking to do something like this?:

$(document).ready(function() {
    doSomething();
});

Upvotes: 1

Jason Lewis
Jason Lewis

Reputation: 1314

Raul is right, it would help to have the code...

But based on my experience with this, what you want is something more along the lines of:

var doSomething = function() {
  alert('hi');
}

$(document).ready(function () {
  doSomething();
});

Upvotes: 0

realshadow
realshadow

Reputation: 2585

Try with:

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

Upvotes: 1

Related Questions