Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to execute Jquery code only once??

I have one jquery method and i used call that method on click of a button . So in that code i have one line " $("#loadingMessage").css('padding-top','6%'); " i need this line execute only once when we call that method first time,later that i gone this line .

So please help me to find one way

the entire method script is below

$('#SearchButton').click(function() {                 
         $(".spinner").css('visibility','hidden');

         $("#loadingMessage").css('padding-top','6%'); //I want this line execute only once, i mean first time

         loaderStart();
         document.getElementById('loadinggif3').style.display = "block";
         $("#loadinggif3").show();
         $(".col-sm-9").css('visibility','hidden');
          var str = $('#SearchText').val();
          str = str.trim();
         if(str=="") return false;
        )};
like image 710
Bangalore Avatar asked Jun 06 '14 07:06

Bangalore


People also ask

How do I run a jQuery function only once?

jQuery one() Method The one() method attaches one or more event handlers for the selected elements, and specifies a function to run when the event occurs. When using the one() method, the event handler function is only run ONCE for each element.

What is jQuery once?

The . once() function takes one or two parameters: if there's just one and if it's a string, it filters out all elements which already have the processing function with that label run. If there is a second parameter, it runs that function for each matched elements that has not yet been processed, similar to . each() .

How do I stop a jQuery script?

The stop() method is an inbuilt method in jQuery which is used to stop the currently running animations for the selected element. Syntax: $(selector). stop(stopAll, goToEnd);


2 Answers

Use jQuery .one(). When using .one() method, the event handler function is only run once for each element.

$('#SearchButton').one("click", function () {
    $("#loadingMessage").css('padding-top', '6%');
});

$('#SearchButton').click(function () {
    $(".spinner").css('visibility', 'hidden');

    loaderStart();
    document.getElementById('loadinggif3').style.display = "block";
    $("#loadinggif3").show();
    $(".col-sm-9").css('visibility', 'hidden');
    var str = $('#SearchText').val();
    str = str.trim();
    if (str == "") return false;
});
like image 184
hyperbeam22 Avatar answered Sep 17 '22 20:09

hyperbeam22


Use a boolean as a global variable, like

var flag = true;

Now, set the condition before the execution, Like

if(flag){  
   $("#loadingMessage").css('padding-top','6%');  
   flag=false;  
}
like image 23
Sudip Pal Avatar answered Sep 19 '22 20:09

Sudip Pal