I want a js function executed once in my code.Either in resize or load handler
.I have a function which is executed if one statement is true and another in the window resize.So when my statement is true then the function is executed and i do not want the function executed again if the window is resized.
My js codes are
if(vertical){
vertical();
}
And
$(window).resize(function(){
vertical();
}
And
var vertical = function(){
..........
}
i also prevent execution if window is resized multiple times
You have to use some kind of flags for that:
var flag = false;
function vertical() {
if (!flag) {
flag = true;
// do your job
}
}
You could solve this via a semaphore.
So you set a flag to false and before you call the function you only want to call once check if(flag) , execute the code and set flag to true
Add a variable to check if the function is fired
var execute = true;
if(vertical){
if (execute) {
vertical();
execute = false;
}
}
$(window).resize(function(){
if (execute) {
vertical();
execute = false;
}
}
Just use unbind function at the end of vertical() function so when it will execute at first it will unbind the event for next window resize.
Related
I have created functions that call other functions like
function abc()
{
def();
}
function def()
{
xyz();
}
Lets say def() is called and at any moment I have a button
<button>STOP</button>
if I press it the execution terminates that means if the execution is run again it should run again from start.
I have seen other solutions in SO but they show how to pause a loop. Can anyone help me out?
You could use a variable to determine whether your code runs or terminates:
var abort = false;
function abc()
{
if (abort) {
return;
}
def();
}
function def()
{
if (abort) {
return;
}
xyz();
}
<button onclick="abort = true">STOP</button>
The only thing you'd have to add is to reset abort back to false whenever you're triggering the main functionality.
I write a function for checking image height and width. You can find my code below. It works but I have a problem with return false: it does not work.
$("#published").click(function( event ){
var img = $('<img src="'+selectedImage+'"/>').load(function( event ){
var orgWidth = this.width;
var orgHeight = this.height;
console.log(orgWidth+" = "+orgHeight);
if(orgWidth >= 169 && orgHeight >= 169){
thisValidate.parent('div.rwmb-input').children('.imageError').remove();
return true;
}else{
event.preventDefault();
if(thisValidate.parent('div.rwmb-input').children('.imageError').length == 0){
thisValidate.parent('div.rwmb-input').append("<p class='imageError'></p>");
}
thisValidate.parent('div.rwmb-input').children('.imageError').html('<br/><label for="techranger_booked_feature_images" class="error">Upload Image More then 169 x 169</label>');
return false;
}
});
});
I have added event.preventDefault(); but it did not help as well.
You are returning to the load() function which isn't going to return to the outer click function.
Also load() is asynchronous so the click event will be completed long before load().
Finally you have 2 event arguments and the one inside load isn't going to have any impact on the click
You would need to prevent the click completely and trigger the next event manually when the load() succeeds.
$("#published").click(function( event ){
event.preventDefault();// prevent default
// no access to "this" inside load() so store reference to form
var $form = $(this).closest('form');
var img = $('<img src="'+selectedImage+'"/>').load(function(imgEvt ){
// code removed for clarity
if(orgWidth >= 169 && orgHeight >= 169){
/* trigger form submit */
$form.submit();
}else{
// other code
}
});
});
Firstly, your return false is running in the scope of the function which serves the load event and your event is an event of jQuery load function.
Secondly, if you want to do it on the button, you cannot do it synchronously like you try to do because the request to get your image is asynchronous, so it happens after your function on button event is finished (so you can't stop the event default behavior because it is already happened). You are forced to prevent / return false in the click method regardless of the image size and then call another function when the check is (un-?)successful to go on. This is the only way.
$("#published").click(function(event){
// here your check, e.g. if (imageFits) goOnFunction();
event.preventDefault();
});
And finally you absolutely do not need jQuery here:
var myImage = new Image();
myImage.src = 'http://okolo.me/wp-content/uploads/2015/07/5998.jpg';
myImage.onload = function() {
// here you can use myImage.width and myImage.height
};
I am trying to get onbeforeunload to work with a set timer of sorts but I can't seem to get it to fire up when the return is in place. I am hoping it would work with a timer but for some reason the timer isn't working. Here is the code I am working and thank you for your help in looking at it much appreciated.
var validNavigation = false;
function wireUpEvents() {
var leave_message = 'Leaving the page';
jQuery(
function goodbye() {
jQuery(window).bind('onbeforeunload', function() {
setTimeout(function() {
setTimeout(function() {
jQuery(document.body).css('background-color', 'red');
}, 10000);
},1);
return leave_message;
});
});
function leave() {
if(!validNavigation) {
killSession();
}
}
//set event handlers for the onbeforeunload and onunloan events
window.onbeforeunload = goodbye;
window.onunload=leave;
}
// Wire up the events as soon as the DOM tree is ready
jQuery(document).ready(function () {
wireUpEvents();
});
onBeforeUnload doesn't work with setTimeout. After onBeforeUnload executes, onUnload will be triggered and the page will change. This happens before the setTimeout callback is called.
#Jonh Kurlak is right, onbeforeunload doenst work with timeout to protect the browser user from being scammed.
But there is something you can do!!!
for(var i = 0; i < 1000; i++){
console.log(i);
}
You can make this for loop printing to console to delay the unload of the page, the higher the number of iterations it as to loop through the longer it waits.
I have a JavaScript event listener function that waits for a user to click on any link then shows a loading box then progresses onto next page.
If a user then clicks the back button it still shows the loading box? Is there a way I can remove it without having to force refresh?
function loading_show() {
document.getElementById("loading").removeAttribute("style");
}
// Function to add event listener to t
function load() {
var el = document.getElementsByTagName("a");
for (var i = 0; i < el.length; i++)
{
el[i].addEventListener("click", loading_show, false);
}
}
function init() {
// quit if this function has already been called
if (arguments.callee.done) return;
// flag this function so we don't do the same thing twice
arguments.callee.done = true;
// do stuff
load();
};
var _timer = setInterval(function() {
if (/loaded|complete/.test(document.readyState)) {
clearInterval(_timer);
init(); // call the onload handler
}
}, 10);
PS. I'm developing for a mobile environment and I don't wish to use jQuery so don't suggest it please.
You can try catching it with the "beforeunload" event.
Here's how to use it:
catching beforeunload confirmation canceled?
I'm using the $(window).scroll(); to specify a function to be call for when the user scrolls too close to the top or bottom.
The function takes a second to execute, and if they continue scrolling, it executes multiple times before the first one has even finished.
Is there any way I can let the function start executing and then tell the $(window).scroll() function that it needs to wait before executing that function again?
You could set a boolean that you're already checking scroll position:
checkingPosition = false;
$window.scroll(function() {
if(checkingPosition) return;
checkingPosition = true;
//do stuff
checkingPosition = false;
});
I'd do something like this to avoid scope issues/confusion by encapsulating the data into an object... in this case, the jQuery object (on the window element):
$(function() {
$(window).data('checking_scroll',false);
$(window).scroll(function() {
if($(this).scrollTop() >= 200 /* or whatever... */) {
if($(this).data('checking_scroll') === true) {
return false;
} else {
whatever_function();
}
}
});
});
function whatever_function() {
$(window).data('checking_scroll',true);
// do all your stuff...
$(window).data('checking_scroll',false);
}
... but that's just me.