Why jQuery doing unwanted multiple actions of single command? - javascript

When i resize browser the it gives multiple alerts. I used "return false" not working.
If I used unbind()/unbind('resize') then it works but it creates an other problem- the resize() function stops working from second time browser/window resize.
My code-
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
alert($(".myclass").parent().width());
$(window).bind('resize',function() {
alert($(".myclass").parent().width());
});
});
</script>
<section class="myclass"></section>

This is not an issue with jQuery, but on the browser's implementation of resize.
Depending which browser you use it may trigger intermediate resizes, or a resize when your mouse is released only.

Because the resize triggers everytime the browser changes.
If you are resizing 100 pixels it can trigger up to 100 times.
Something like this should work and trigger only once you stopped resizing the window:
var resizing = false, stopedResizing = true;
$(window).bind('resize',function() {
if(!resizing){
console.log("started resizing. Width = " + $(".myclass").parent().width());
resizing = true;
}
stopedResizing = false;
setTimeout(function(){
if(!stopedResizing){
stopedResizing = true;
setTimeout(function(){
if(stopedResizing && resizing){
resizing = false;
console.log('Stoped resizing. Width = ' + $(".myclass").parent().width());
}
}, 500);
}
}, 500);
});

You could do something like:
$(document).ready(function(e) {
alert($(".myclass").parent().width());
var lastTime = 0;
$(window).bind('resize',function() {
var currentTime = new Date().time();
if(currentTime > lastTime + 5000)
alert($(".myclass").parent().width());
lastTime = currentTime;
});
});
...so that it will only fire on resizes at least 5 seconds apart. Normally though, you'd want to act when resizing stops, not when it starts.

This code fires ones on mouseover of the window after the a resize event as occurred.
$(document).ready(function() {
var windowResized = false;
function callFunction() {
console.log("I am called once after window resize");
}
$(window).mouseover(function() {
if (windowResized == true) {
callFunction();
windowResized = false;
}
})
$(window).resize(function() {
windowResized = true;
});
})

Related

Update div content in real time with jQuery

I'm pretty new to web design, and I wanted to make a rectangle which says "true" if the user has scrolled, and turn to "false" after one second has passed.
var hasScroll = false;
$(document).ready(function() {
$(window).scroll(function() {
hasScroll = true;
$("#rectangle").html(hasScroll.toString());
setTimeout(function() {
hasScroll = false;
}, 1000);
});
});
body { height: 800px }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rectangle"></div>
However, even though the variable "hasScroll" changes exactly how I want, I can't seem to find a way to make the div show the hasScroll status in real-time.
You'll need to set the #rectangle's text again after the scrolling is done. You'll also probably want to set/clear a setTimeout that only runs once no scroll events have been triggered for 1000ms:
let scrollingTimeout;
const rectangle = document.querySelector('#rectangle');
$(window).scroll(function() {
if (scrollingTimeout) clearTimeout(scrollingTimeout);
else rectangle.textContent = 'true';
scrollingTimeout = setTimeout(function() {
console.log('setting text to false');
rectangle.textContent = 'false';
scrollingTimeout = null;
}, 1000);
});
body {
height: 800px
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="rectangle">abc</div>
It's very simple, Just put the same line $("#rectangle").html(hasScroll.toString()); after setting hasScroll = false;
For ex.,
var hasScroll = false;
$(document).ready(function() {
$(window).scroll(function() {
hasScroll = true;
$("#rectangle").html(hasScroll.toString());
setTimeout(function() {
hasScroll = false;
$("#rectangle").html(hasScroll.toString()); // To show false
}, 1000);
});
});

vertical scroll two tables at the same time

I have two tables that must scroll together:
$('.vscroll').on('scroll', function (e) {
divTable1.scrollTop = e.scrollTop;
divTable2.scrollTop = e.scrollTop;
There's a little lag issue though. Table1 scrolls milliseconds before Table2.
I know scrollTop fires the scroll event, but is there a way to delay the scrolling of Table1 until Table2's scrollTop is also set?
Try using a setTimeout to trigger the scrolls, and then return false to cancel the original scrollevent:
var ignoreEvent = false;
$(".vscroll").on('scroll', function (e) {
if (!ignoreEvent) {
setTimeout(function() {
ignoreEvent = true;
table1.scrollTop = e.scrollTop;
table2.scrolLTop = e.scrollTop;
}, 100);
}
ignoreEvent = false;
return false; // cancels the original scroll event.
}
I'm using divs instead of tables but you get the idea
$("div").on("scroll",function(){
$("div:not(this)").scrollTop($(this).scrollTop());
});
DEMO

window.onresize fires twice

I'm new to js. Please, don't kick painfully.
I have this code
window.onresize=function() {alert(1);};
When I resize any browser`s window, this function fires twice. Why? And how to rewrite this code that code will fire once.
Thanx in advance.
You need a timeout to bundle the resize events.
var res;
window.onresize=function() {
if (res){clearTimeout(res)};
res = setTimeout(function(){console.log("resize triggered");},100);
};
live Example
This event will fire multiple times in different browsers (some once you've finished the the resize, others during).
One way to get around this is to wait a certain amount of time (say half a second) after the event fires, to see if there are further updates. If not, you can proceed with the alert.
e.g.
var resizeTimer;
window.onresize = function(){
if (resizeTimer){
clearTimeout(resizeTimer);
}
resizeTimer = setTimeout(function(){
alert(1);
}, 500);
};
See it work on this fiddle.
To prevent function from "firing" the same result more than once when user resize
var doc = document; //To access the dom only once
var cWidth = doc.body.clientWidth;
var newWidth = cWidth; //If you want a log to show at startup, change to: newWidth = 0
window.onresize = function (){
newWidth = doc.body.clientWidth;
if(cWidth != newWidth){
cWidth = newWidth;
console.log("clientWidth:", cWidth); //instead of alert(cWidth);
};
};
I propose other solution because I don't like the timeouts,
`var resized;
window.onresize = function () {
if(resized){
resized = false;
}
else{
resized = true;
alert('resize');
}
};`

Adding listener for position on screen

I'd like to set something up on my site where when you scroll within 15% of the bottom of the page an element flyouts from the side... I'm not sure how to get started here... should I add a listener for a scroll function or something?
I'm trying to recreate the effect at the bottom of this page: http://www.nytimes.com/2011/01/25/world/europe/25moscow.html?_r=1
update
I have this code....
console.log(document.body.scrollTop); //shows 0
console.log(document.body.scrollHeight * 0.85); //shows 1038.7
if (document.body.scrollTop > document.body.scrollHeight * 0.85) {
console.log();
$('#flyout').animate({
right: '0'
},
5000,
function() {
});
}
the console.log() values aren't changing when I scroll to the bottom of the page. The page is twice as long as my viewport.
[Working Demo]
$(document).ready(function () {
var ROOT = (function () {
var html = document.documentElement;
var htmlScrollTop = html.scrollTop++;
var root = html.scrollTop == htmlScrollTop + 1 ? html : document.body;
html.scrollTop = htmlScrollTop;
return root;
})();
// may be recalculated on resize
var limit = (document.body.scrollHeight - $(window).height()) * 0.85;
var visible = false;
var last = +new Date;
$(window).scroll(function () {
if (+new Date - last > 30) { // more than 30 ms elapsed
if (visible && ROOT.scrollTop < limit) {
setTimeout(function () { hide(); visible = false; }, 1);
} else if (!visible && ROOT.scrollTop > limit) {
setTimeout(function () { show(); visible = true; }, 1);
}
last = +new Date;
}
});
});
I know this is an old topic, but the above code that received the check mark was also triggering the $(window).scroll() event listener too many times.
I guess twitter had this same issue at one point. John Resig blogged about it here: http://ejohn.org/blog/learning-from-twitter/
$(document).ready(function(){
var ROOT = (function () {
var html = document.documentElement;
var htmlScrollTop = html.scrollTop++;
var root = html.scrollTop == htmlScrollTop + 1 ? html : document.body;
html.scrollTop = htmlScrollTop;
return root;
})();
// may be recalculated on resize
var limit = (document.body.scrollHeight - $(window).height()) * 0.85;
var visible = false;
var last = +new Date;
var didScroll = false;
$(window).scroll(function(){
didScroll = true;
})
setInterval(function(){
if(didScroll){
didScroll = false;
if (visible && ROOT.scrollTop < limit) {
hideCredit();
visible = false;
} else if (!visible && ROOT.scrollTop > limit) {
showCredit();
visible = true;
}
}
}, 30);
function hideCredit(){
console.log('The hideCredit function has been called.');
}
function showCredit(){
console.log('The showCredit function has been called.');
}
});
So the difference between the two blocks of code is when and how the timer is called. In this code the timer is called off the bat. So every 30 millaseconds, it checks to see if the page has been scrolled. if it's been scrolled, then it checks to see if we've passed the point on the page where we want to show the hidden content. Then, if that checks true, the actual function then gets called to show the content. (In my case I've just got a console.log print out in there right now.
This seems to be better to me than the other solution because the final function only gets called once per iteration. With the other solution, the final function was being called between 4 and 5 times. That's got to be saving resources. But maybe I'm missing something.
bad idea to capture the scroll event, best to use a timer and every few milliseconds check the scroll position and if in the range you need then execute the necessary code for what you need
Update: in the past few years the best practice is to subscribe to the event and use a throttle avoiding excessive processing https://lodash.com/docs#throttle
Something like this should work:
$(window).scroll(function() {
if (document.body.scrollTop > document.body.scrollHeight * 0.85) {
// flyout
}
});
document.body.scrollTop may not work equally well on all browsers (it actually depends on browser and doctype); so we need to abstract that in a function.
Also, we need to flyout only one time. So we can unbind the event handler after having flyed out.
And we don't want the flyout effect to slow down scrolling, so we will run our flytout function out of the event loop (by using setTimeout()).
Here is the final code:
// we bind the scroll event, with the 'flyout' namespace
// so we can unbind easily
$(window).bind('scroll.flyout', (function() {
// this function is defined only once
// it is private to our event handler
function getScrollTop() {
// if one of these values evaluates to false, this picks the other
return (document.documentElement.scrollTop||document.body.scrollTop);
}
// this is the actual event handler
// it has the getScrollTop() in its scope
return function() {
if (getScrollTop() > (document.body.scrollHeight-$(window).height()) * 0.85) {
// flyout
// out of the event loop
setTimeout(function() {
alert('flyout!');
}, 1);
// unbind the event handler
// so that it's not call anymore
$(this).unbind('scroll.flyout');
}
};
})());
So in the end, only getScrollTop() > document.body.scrollHeight * 0.85 is executed at each scroll event, which is acceptable.
The flyout effect is ran only one time, and after the event has returned, so it won't affect scrolling.

Event when user stops scrolling

I'd like to do some fancy jQuery stuff when the user scrolls the page. But I have no idea how to tackle this problem, since there is only the scroll() method.
Any ideas?
You can make the scroll() have a time-out that gets overwritten each times the user scrolls. That way, when he stops after a certain amount of milliseconds your script is run, but if he scrolls in the meantime the counter will start over again and the script will wait until he is done scrolling again.
Update:
Because this question got some action again I figured I might as well update it with a jQuery extension that adds a scrollEnd event
// extension:
$.fn.scrollEnd = function(callback, timeout) {
$(this).on('scroll', function(){
var $this = $(this);
if ($this.data('scrollTimeout')) {
clearTimeout($this.data('scrollTimeout'));
}
$this.data('scrollTimeout', setTimeout(callback,timeout));
});
};
// how to call it (with a 1000ms timeout):
$(window).scrollEnd(function(){
alert('stopped scrolling');
}, 1000);
<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>
<div style="height: 200vh">
Long div
</div>
Here is a simple example using setTimeout to fire a function when the user stops scrolling:
(function() {
var timer;
$(window).bind('scroll',function () {
clearTimeout(timer);
timer = setTimeout( refresh , 150 );
});
var refresh = function () {
// do stuff
console.log('Stopped Scrolling');
};
})();
The timer is cleared while the scroll event is firing. Once scrolling stops, the refresh function is fired.
Or as a plugin:
$.fn.afterwards = function (event, callback, timeout) {
var self = $(this), delay = timeout || 16;
self.each(function () {
var $t = $(this);
$t.on(event, function(){
if ($t.data(event+'-timeout')) {
clearTimeout($t.data(event+'-timeout'));
}
$t.data(event + '-timeout', setTimeout(function () { callback.apply($t); },delay));
})
});
return this;
};
To fire callback after 100ms of the last scroll event on a div (with namespace):
$('div.mydiv').afterwards('scroll.mynamespace', function(e) {
// do stuff when stops scrolling
$(this).addClass('stopped');
}, 100
);
I use this for scroll and resize.
Here is another more generic solution based on the same ideas mentioned:
var delayedExec = function(after, fn) {
var timer;
return function() {
timer && clearTimeout(timer);
timer = setTimeout(fn, after);
};
};
var scrollStopper = delayedExec(500, function() {
console.log('stopped it');
});
document.getElementById('box').addEventListener('scroll', scrollStopper);
I had the need to implement onScrollEnd event discussed hear as well.
The idea of using timer works for me.
I implement this using JavaScript Module Pattern:
var WindowCustomEventsModule = (function(){
var _scrollEndTimeout = 30;
var _delayedExec = function(callback){
var timer;
return function(){
timer && clearTimeout(timer);
timer = setTimeout(callback, _scrollEndTimeout);
}
};
var onScrollEnd = function(callback) {
window.addEventListener('scroll', _delayedExec(callback), false);
};
return {
onScrollEnd: onScrollEnd
}
})();
// usage example
WindowCustomEventsModule.onScrollEnd(function(){
//
// do stuff
//
});
Hope this will help / inspire someone
Why so complicated? As the documentation points out, this http://jsfiddle.net/x3s7F/9/ works!
$('.frame').scroll(function() {
$('.back').hide().fadeIn(100);
}
http://api.jquery.com/scroll/.
Note: The scroll event on Windows Chrome is differently to all others. You need to scroll fast to get the same as result as in e.g. FF. Look at https://liebdich.biz/back.min.js the "X" function.
Some findings from my how many ms a scroll event test:
Safari, Mac FF, Mac Chrome: ~16ms an event.
Windows FF: ~19ms an event.
Windows Chrome: up to ~130ms an event, when scrolling slow.
Internet Explorer: up to ~110ms an event.
http://jsfiddle.net/TRNCFRMCN/1Lygop32/4/.
There is no such event as 'scrollEnd'. I recommend that you check the value returned by scroll() every once in a while (say, 200ms) using setInterval, and record the delta between the current and the previous value. If the delta becomes zero, you can use it as your event.
There are scrollstart and scrollstop functions that are part of jquery mobile.
Example using scrollstop:
$(document).on("scrollstop",function(){
alert("Stopped scrolling!");
});
Hope this helps someone.
The scrollEnd event is coming. It's currently experimental and is only supported by Firefox. See the Mozilla documentation here - https://developer.mozilla.org/en-US/docs/Web/API/Document/scrollend_event
Once it's supported by more browsers, you can use it like this...
document.onscrollend = (event) => {
console.log('Document scrollend event fired!');
};
I pulled some code out of a quick piece I cobbled together that does this as an example (note that scroll.chain is an object containing two arrays start and end that are containers for the callback functions). Also note that I am using jQuery and underscore here.
$('body').on('scroll', scrollCall);
scrollBind('end', callbackFunction);
scrollBind('start', callbackFunction);
var scrollCall = function(e) {
if (scroll.last === false || (Date.now() - scroll.last) <= 500) {
scroll.last = Date.now();
if (scroll.timeout !== false) {
window.clearTimeout(scroll.timeout);
} else {
_(scroll.chain.start).each(function(f){
f.call(window, {type: 'start'}, e.event);
});
}
scroll.timeout = window.setTimeout(self.scrollCall, 550, {callback: true, event: e});
return;
}
if (e.callback !== undefined) {
_(scroll.chain.end).each(function(f){
f.call(window, {type: 'end'}, e.event);
});
scroll.last = false;
scroll.timeout = false;
}
};
var scrollBind = function(type, func) {
type = type.toLowerCase();
if (_(scroll.chain).has(type)) {
if (_(scroll.chain[type]).indexOf(func) === -1) {
scroll.chain[type].push(func);
return true;
}
return false;
}
return false;
}

Categories

Resources