Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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();
});
like image 456
Linda Avatar asked Sep 08 '11 21:09

Linda


1 Answers

        // 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.

like image 169
iOSAndroidWindowsMobileAppsDev Avatar answered Oct 24 '22 10:10

iOSAndroidWindowsMobileAppsDev