window resize only works once - javascript

I've got a function within a window.resize event and it works well, apart from that it seems to only works once. If the user resizes the window again the function isn't executed. This is the code:
$(window).resize(function() {
var wait = setInterval(function () {
if (!$(currentBanner, loading).is(":animated")) {
clearInterval(wait);
loading.stop().fadeOut(300, function () {
if ($('#banner').css('display') == 'block'){
setTimeout(function() {
bannerInit();
}, 800);
startInterval();
if (initialLoad) {
initialLoad = false;
next.slideDown();
previous.slideDown();
}
}
});
}
}, 200);
}).resize();
Anybody know how I can make sure that the function is executed every time the window is resized?

I don't know what was your intention but if it was to have a delayed execution after the window resize you should change setInterval to setTimeout
setInterval is a infinite loop that runs until you tell it to stop and setTimeout is only executed once and it will wait x milliseconds to be executed.
Plus, you dont need to call 'resize()' event, it will be fired everytime the window size is changed by any reason (user resizing or maximizing, etc)
$(window).on("resize",function() {
var wait = setTimeout(function () {
if (!$(currentBanner, loading).is(":animated")) {
clearInterval(wait);
loading.stop().fadeOut(300, function () {
if ($('#banner').css('display') == 'block'){
setTimeout(function() {
bannerInit();
}, 800);
startInterval();
if (initialLoad) {
initialLoad = false;
next.slideDown();
previous.slideDown();
}
}
});
}
}, 200);
});

That's because you're calling .resize() at the end of the event definition.
Try changing to:
$(window).resize(function () {
//....
});
$(window).resize();

Related

Unable to reset setTimeout timer in JavaScript

Here is my pseudocode:
if(key.pressed = 'a') {
activate = true;
}
var mytimeout = function timer_function() {
// Do stuff;
setTimeout( function() {
// do more stuff
}, 5000);
}
function some_function() {
if(activated) {
// do stuff
clearTimeout(mytimeout);
timer_function();
}
}
if(mouse.click == true) {
some_function();
}
I want the timer to be reset on each mouse click which calls some_function(). What actually happens is that the time is set on first click but never resets after that.
What am I missing?
Thanks.
mytimeout is a function, not a timeout handle. What you need to store is the result of the setTimeout call like this.
var timeoutHandle;
function timer_function() {
// Do stuff;
timeoutHandle = setTimeout( function() {
// do more stuff
}, 5000);
}
function some_function() {
if(activated) {
// do stuff
clearTimeout(timeoutHandle);
timer_function();
}
}
In function timer_function return the value of setTimeout
var mytimeout = function timer_function() {
return setTimeout( function() {
//Do some more stuff
}, 5000);
}
Thats because in you are only going to replay the Timeout only when the user presses the "a" key. I don't know why you kept it like that but thats probably the reason.!

Wait until div is not visible to process next line

I need to write some code which is supposed to wait until a predefined div is no longer visible in order to process the next line. I plan on using jQuery( ":visible" ) for this, and was thinking I could have some type of while loop. Does anyone have a good suggestion on how to accomplish this task?
$( document ).ready(function() {
$(".scroller-right" ).mouseup(function( event ) {
alert('right');
pollVisibility();
});
});
function pollVisibility() {
if ($(".mstrWaitBox").attr("visibility")!== 'undefined') || $(".mstrWaitBox").attr("visibility") !== false) {
alert('inside else');
microstrategy.getViewerBone().commands.exec('refresh');
} else {
setTimeout(pollVisibility, 100);
}
}
$( document ).ready(function() {
$(".scroller-right" ).mouseup(function( event ) {
alert('right');
pollVisibility();
});
});
function pollVisibility() {
if (!$(".mstrWaitBox").is(":visible")) {
alert('inside if');
microstrategy.getViewerBone().commands.exec('refresh');
} else {
setTimeout(pollVisibility, 100);
}
}
div when not visible:
<div class=​"mstrWaitBox" id=​"divWaitBox" scriptclass=​"mstrDialogImpl" dg=​"1" ty=​"edt">​
</div>​
div when visible:
<div class=​"mstrWaitBox" id=​"divWaitBox" scriptclass=​"mstrDialogImpl" dg=​"1" ty=​"edt" visibility="visible">​
</div>​
You can use the setTimeout function to poll the display status of the div. This implementation checks to see if the div is invisible every 1/2 second, once the div is no longer visible, execute some code. In my example we show another div, but you could easily call a function or do whatever.
http://jsfiddle.net/vHmq6/1/
Script
$(function() {
setTimeout(function() {
$("#hideThis").hide();
}, 3000);
pollVisibility();
function pollVisibility() {
if (!$("#hideThis").is(":visible")) {
// call a function here, or do whatever now that the div is not visible
$("#thenShowThis").show();
} else {
setTimeout(pollVisibility, 500);
}
}
}
Html
<div id='hideThis' style="display:block">
The other thing happens when this is no longer visible in about 3s</div>
<div id='thenShowThis' style="display:none">Hi There</div>
If your code is running in a modern browser you could always use the MutationObserver object and fallback on polling with setInterval or setTimeout when it's not supported.
There seems to be a polyfill as well, however I have never tried it and it's the first time I have a look at the project.
FIDDLE
var div = document.getElementById('test'),
divDisplay = div.style.display,
observer = new MutationObserver(function () {
var currentDisplay = div.style.display;
if (divDisplay !== currentDisplay) {
console.log('new display is ' + (divDisplay = currentDisplay));
}
});
//observe changes
observer.observe(div, { attributes: true });
div.style.display = 'none';
setTimeout(function () {
div.style.display = 'block';
}, 500);
However an even better alternative in my opinion would be to add an interceptor to third-party function that's hiding the div, if possible.
E.g
var hideImportantElement = function () {
//hide logic
};
//intercept
hideImportantElement = (function (fn) {
return function () {
fn.apply(this, arguments);
console.log('element was hidden');
};
})(hideImportantElement);
I used this approach to wait for an element to disappear so I can execute the other functions after that.
Let's say doTheRestOfTheStuff(parameters) function should only be called after the element with ID the_Element_ID disappears, we can use,
var existCondition = setInterval(function() {
if ($('#the_Element_ID').length <= 0) {
console.log("Exists!");
clearInterval(existCondition);
doTheRestOfTheStuff(parameters);
}
}, 100); // check every 100ms

Detecting if browser window is active and start event after window is active again [JavaScript]

The idea is simple: I have buttons which refer to another website. Whenever the user has clicked more than two links I want to refresh some content (through Ajax). For that to work I need to detect if my window is active or not, since I only want the event to start when the user is BACK on my page.
Without further ado this is my code:
$(document).on("click", "a", function() {
numberOfClicks += 1;
if (numberOfClicks >= 2)
{
userOnWebsiteOrNot();
numberOfClicks = 0;
}
});
function userOnWebsiteOrNot()
{
if (focusedOrNot == 0)
{
$('#resultaat').hide().fadeIn(5000);
}
}
window.addEventListener('focus', function() {
document.title = 'focused';
focusedOrNot = 0;
});
window.addEventListener('blur', function() {
document.title = 'not focused';
focusedOrNot = 1;
});
It DOES detect whenever the user is on the page or not, but somehow the fade always happens.
Could anybody explain me what I'm doing wrong or give me any ideas?
Thanks
Yenthe
ANSWER:
I needed a setTimeOut on three functions because they would otherwise check too fast. Thank you for that help Romo! ;) All credit goes to Romo to be honest.
$(document).on("click", "a", function() {
numberOfClicks += 1;
if (numberOfClicks >= 2)
{
haallinks();
setTimeout(function() {
userOnWebsiteOrNot();
}, 2000);
numberOfClicks = 0;
}
});
function userOnWebsiteOrNot()
{
if (focusedOrNot === 0)
{
$('#resultaat').hide().fadeIn(5000);
}
else
{
controlerenActiefOfNiet();
}
}
function controlerenActiefOfNiet()
{
setTimeout(function() {
userOnWebsiteOrNot();
}, 2000);
}
window.addEventListener('focus', function() {
setTimeout(function() {
focusedOrNot = 0;
}, 0);
});
window.addEventListener('blur', function() {
setTimeout(function() {
focusedOrNot = 1;
}, 1000);
});
I think the problem is that when you click a link the second time the window will always be focused. JS runs pretty fast. To overcome this, I think you should do a setTimeout() and delay it 200ms or so to give the window time to "lose" focus
setTimeout(function() {userOnWebsiteOrNot(); },2000);
http://jsfiddle.net/xVHgE/
Edit: Adding delay to event listener. I don't think you can "delay" an event though, just the function it runs.
window.addEventListener('focus', function() {
setTimeout( function() {
$('#test').html('focus');
focusedOrNot = 0;
} , 5000);
});

Temporarily disabling javascript function from repeating after mouseleave

I have an image gallery that rotates through the rotator class divs on www.creat3dprinters.com that pauses on mouseenter and then fires again 1 second after mouseleave.
However, if a user moves the mouse in and out of the rotator class div quickly the function calls stack up and the visible changes until the 'stack' is completed.
I want the 1 second delay that has not been completed to be cancelled on the 2nd and subsequent mouseenter so that this does not happen.
I have tried using clearTimeout within the mouseenter function but it does not seem to work.
I know there is also the stop() function but that did not work either.
Any suggestions greatly appreciated.
jQuery(document).ready(function () {
var initList = setInterval('RotateIt()', 4000);
$('.rotator').mouseenter(function () {
clearInterval(initList);
}).mouseleave(function () {
timeout = setTimeout(function () {
RotateIt()
}, 1000);
initList = setInterval('RotateIt()', 4000);
})
});
function RotateIt() {
clearTimeout(timeout);
if ($('#rotator-visible').next('.rotator').length == 0) {
$('.rotator:first').attr('id', 'rotator-visible');
$('.rotator:last').removeAttr("id");
} else {
$('#rotator-visible').removeAttr("id").next('.rotator').attr("id", "rotator-visible");
}
}
If a user moves the mouse in and out of the rotator class div quickly the function calls stack up
Then clearTimeout it - and in exactly that place, not only in the delayed RotateIt. The simplest solution would be to call clearTimeout every time before setTimeout, so that you can be sure there is only one active timeout at once.
jQuery(document).ready(function($) {
var initList = setInterval(rotateIt, 4000),
delay = null;
$('.rotator').mouseenter(function(e) {
clearInterval(initList);
}).mouseleave(function(e) {
clearTimeout(delay);
delay = setTimeout(function () {
rotateIt();
initList = setInterval(rotateIt, 4000);
}, 1000);
})
});
function rotateIt() {
if ($('#rotator-visible').next('.rotator').length == 0) {
$('.rotator:first').attr('id', 'rotator-visible');
$('.rotator:last').removeAttr("id");
} else {
$('#rotator-visible').removeAttr("id").next('.rotator').attr("id", "rotator-visible");
}
}

Jquery: mousedown effect (while left click is held down)

I need a function that executes a function while a button is pressed and stops executing when the button is let go
$('#button').--while being held down--(function() {
//execute continuously
});
I believe something like this would work:
var timeout, clicker = $('#clicker');
clicker.mousedown(function(){
timeout = setInterval(function(){
// Do something continuously
}, 500);
return false;
});
$(document).mouseup(function(){
clearInterval(timeout);
return false;
});
See this demo: http://jsfiddle.net/8FmRd/
A small modification to the original answer:
$('#Clicker').mousedown(function () {
//do something here
timeout = setInterval(function () {
//do same thing here again
}, 500);
return false;
});
$('#Clicker').mouseup(function () {
clearInterval(timeout);
return false;
});
$('#Clicker').mouseout(function () {
clearInterval(timeout);
return false;
});
With the mouseout event on the Clicker it stops when you move your mouse out of the click area.
The reason why I suggest to do the same thing twice is to get a smoother effect. If you don't do it once before the timeout is set it will be a delay of, in this case, 500ms before something happens.
Here's a pure JavaScript implementation of the supplied solutions which has extended support for touch screens. You supply the id, action to perform (function(){}) and the interval (ms) to repeat the action. Note that this implementation will also execute the action immediately, rather than waiting for the interval to lapse.
// Configures an element to execute a function periodically whilst it holds the user's attention via a mouse press and hold.
function assertPeriodicPress(id, action, interval) {
// Listen for the MouseDown event.
document.getElementById(id).addEventListener('mousedown', function(ev) { action(); timeout = setInterval(action, interval); return false; }, false);
// Listen for mouse up events.
document.getElementById(id).addEventListener('mouseup', function(ev) { clearInterval(timeout); return false; }, false);
// Listen out for touch end events.
document.getElementById(id).addEventListener('touchend', function(ev) { clearInterval(timeout); return false; }, false);
}
$.fn.click2=function(cb,interval){
var timeout;
if(!interval) interval=100;
$(this).mousedown(function () {
var target=this;
timeout = setInterval(function(){
cb.apply(target);
}, interval);
return false;
}).mouseup(function () {
clearInterval(timeout);
return false;
}).mouseout(function () {
clearInterval(timeout);
return false;
});
}

Categories

Resources