How to Execute Jquery Code Only Once

How to execute Jquery code only once??

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

How to run a function only once with jquery?

.one() will trigger an event once, everytime the page is loaded so wouldn't work for your example.

As another answer has said, you could use cookies, something like this:

// get the cookie if its there
var popUpShown = getCookie('popUpShown');
var numberOfDaysCookieExpiresIn = 99999999999;

// check the cookie to see if the popup has been shown already
if (popUpShown != '1') {
window.setTimeout(function() {
$(".alert").fadeTo(500, 0).slideUp(500, function(){
$(this).remove();
});
}, 1500);

// set the cookie so we dont show the pop up again
setCookie('popUpShown', '1', numberOfDaysCookieExpiresIn);
};

Execute jquery only once

you need to have count = 1;

instead of var count = 1; (~line 47)

and count = 0; instead of var count = 0; (line 29)

line 29 (var count = 0;) defines the variable 'count', but count cannot be overridden or increased in your code as it is not in the same scope.

Executing a function only once

Not sure what that code is meant to do, but you can always use a flag variable to control something like that:

var executed = false;
$(".counter").waypoint(function() {
if (!executed) {
executed = true;
$(".counter").count();
}
}, {offset:"100%"});

executing jquery script only once first time when page loads

$(document).ready(function () {
if($.cookie("scriptExecuted")!="yes") {
//Scroll div you the bottom onpage load
$("#divTest").scrollTop($("#divTest")[0].scrollHeight);
$.cookie("scriptExecuted", "yes");
}
});

Use of cookies would be helpful, you can use this lovely jquery plugin to set, unset and retrieve cookie values. https://github.com/carhartl/jquery-cookie

Logic is simple, check for the set cookie, if not set execute, and when executed, set the cookie.

CDN for jQuery-Cookies https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.js

here goes the working fiddle : https://jsfiddle.net/kzLkg1rk/

How to execute action only once in jquery?

Solution was quite simple, I don't know how I missed it:

jQuery(document).ready(function($){
$('.popup-trigger').click(function(){
$(this).closest('.caption').find('.popup');
});
})


Related Topics



Leave a reply



Submit