How to execute Jquery code only once??

Bangalore picture Bangalore · Jun 6, 2014 · Viewed 67.3k times · Source

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;
        )};

Answer

frosdqy picture frosdqy · Jun 6, 2014

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;
});