$(window).resize event not working 100% smoothly - javascript

I run the following code on a page (#home) that should smoothly inject a slider or if the page container is under 480px leave the page as is.
I cannot get the resize event to work 100% smoothly.
If I reduce the window the script (js.slide.js) wont get triggered but the content will be loaded in (slide.php). If I continue to reduce the window a little extra it will all work ok.
Could anyone please advise as to how I could get this working smoothly. The code is as follows
$(document).ready(function(){
if ($("#home").length > 0 ){
var homeSlideShow = {
$promoArea: $('#promo-area'),
$currentContent: $('#promo-area').contents(),
$pageContainer: $('.page'),
init: function(){
var hSS = homeSlideShow;
if (hSS.$pageContainer.width() > 480 ){
hSS.setTheSlideShow();
} else{
hSS.$promoArea.html(hSS.$currentContent);
}
},
setTheSlideShow: function(){
var hSS = homeSlideShow;
$.getScript(myscript_wp_vars.temp_dir + '/js/slide.js', function(){
hSS.$promoArea.load(myscript_wp_vars.temp_dir + '/libs/slide.php #c4u-slide',
function(){
var options = {
preloader: false,
nextButton: true,
prevButton: true,
animateStartingFrameIn: true,
transitionThreshold: 250
};
var sequence = $("#sequence").sequence(options).data("sequence"),
$slideShow = $("#c4u-slide");
});
});
}
};
//
// Check page size
//
if (homeSlideShow.$pageContainer.width() > 480 ){
homeSlideShow.setTheSlideShow();
}
//
// On window resize
//
$(window).resize(function() {
homeSlideShow.init();
});
}// END home.length
});//End $(document).ready(function()
Thanks in advance for any assistance or advice.
Cheers
Noel

window.resize event is triggered multiple times, depending of browser's behaviour. I'll suggest you to try this:
var timeoutResize;
$(window).resize(function(){
if(typeof timeoutResize != 'undefined') clearTimeout(timeoutResize);
timeoutResize = setTimeout(function(){homeSlideShow.init();},50);
});

Related

jQuery "Snap To" Effect

I have a specific effect I want for a website I'm building. As you can see in this website, I want the screen to "snap to" the next section after the user scrolls, but only after (not the instant) the scroll event has fired. The reason I don't want to use a plugin like panelSnap is because I
1: Want smaller code and
2. Want the website, when viewed on mobile, to have more of the "instant snap" effect (try reducing the browser size in the website mentioned above). I know I theoretically could try combining two plugins, like panelsnap and scrollify, and activate them appropriately when the browser is a certain width, but I don't know if I want to do that... :(
So all of that said, here's the code:
var scrollTimeout = null;
var currentElem = 0;
var options = {
scrollSpeed: 1100,
selector: 'div.panels',
scrollDelay: 500,
};
$(document).ready(function() {
var $snapElems = $(options.selector);
console.log($($snapElems[currentElem]).offset().top);
function snap() {
if ($('html, body').scrollTop() >= $($snapElems[currentElem]).offset().top) {
if (currentElem < $snapElems.length-1) {
currentElem++;
}
}else{
if (currentElem > 0) {
currentElem = currentElem - 1;
}
}
$('html, body').animate({
scrollTop: $($snapElems[currentElem]).offset().top
}, options.scrollSpeed);
}
$(window).scroll(function() {
if ($(window).innerWidth() > 766) {
if (scrollTimeout) {clearTimeout(scrollTimeout);}
scrollTimeout = setTimeout(function(){snap()}, options.scrollDelay);
}else{
//I'll deal with this later
}
});
});
My problem is that every time the snap function is called, it triggers the scroll event, which throws it into a loop where the window won't stop scrolling between the first and second elements. Here's the poor, dysfunctional site: https://tcfchurch.herokuapp.com/index.html Thank for the help.
You can use a boolean to record when the scroll animation in snap is in progress and prevent your $(window).scroll() event handler from taking any action.
Here's a working example:
var scrollTimeout = null;
var currentElem = 0;
var options = {
scrollSpeed: 1100,
selector: 'div.panels',
scrollDelay: 500,
};
$(document).ready(function() {
var scrollInProgress = false;
var $snapElems = $(options.selector);
console.log($($snapElems[currentElem]).offset().top);
function snap() {
if ($('html, body').scrollTop() >= $($snapElems[currentElem]).offset().top) {
if (currentElem < $snapElems.length-1) {
currentElem++;
}
}else{
if (currentElem > 0) {
currentElem = currentElem - 1;
}
}
scrollInProgress = true;
$('html, body').animate({
scrollTop: $($snapElems[currentElem]).offset().top
}, options.scrollSpeed, 'swing', function() {
// this function is invoked when the scroll animate is complete
scrollInProgress = false;
});
}
$(window).scroll(function() {
if (scrollInProgress == false) {
if ($(window).innerWidth() > 766) {
if (scrollTimeout) {clearTimeout(scrollTimeout);}
scrollTimeout = setTimeout(function(){snap()}, options.scrollDelay);
}else{
//I'll deal with this later
}
}
});
});
The variable scrollInProgress is set to false by default. It is then set to true when the scroll animate starts. When the animate finishes, scrollInProgress is set back to false. A simple if statement at the top of your $(window).scroll() event handler prevents the handler from taking any action while the animate scroll is in progress.
Have you considered using the well known fullPage.js library for that? Check out this normal scroll example. The snap timeout is configurable through the option fitToSectionDelay.
And nothing to worry about the size... it is 7Kb Gzipped!
I know I theoretically could try combining two plugins, like panelsnap and scrollify, and activate them appropriately when the browser is a certain width, but I don't know if I want to do that
fullPage.js also provides responsiveWidth and responsiveHeight options to turn it off under certain dimensions.

Scroll down to special div

I'm trying to make a simple jQuery plugin that will scroll page down until it reaches special div like a #stopscroll. I got a simple jQuery plugin to stop scroll on special size:
$(window).scroll(checkscroll);
function checkscroll(){
var top = $(window).scrollTop();
if(top > 300){
$('#share_box').fadeOut('slow');
}else{
$('#share_box').fadeIn('slow');
}
}
checkscroll();
How do I make it scroll to a special div instead of scrolling a specified size? I want it to stop scrolling when div #sharebox reach #stopscroll.
I don't know if I understand your question correct but I think I had the same problem a while back. I fixed it like this:
$(document).ready(function() {
/** HIDE MENU **/
$(".menu").css("margin-top", "-88px");
var mustSlideDown = true;
var mustSlideUp = false;
$(window).scroll(function() {
var verschil = ($(window).scrollTop() / 5);
if (verschil > 40 && mustSlideDown) {
$('.menu').animate({'margin-top': '0px' }, {duration: 500, queue: false});
mustSlideDown = false;
mustSlideUp = true;
}
else if (verschil < 40 && mustSlideUp) {
$('.menu').animate({'margin-top': '-88px' }, {duration: 500, queue: false});
mustSlideUp = false;
mustSlideDown = true;
}
});
});
Didn't get much of your English, but maybe you are looking for this-
Window.location='#scollDiv';

How to only run a script if the DIV is in view?

I have a script that I wrote:
jQuery(function($) {
$('.count').countTo({
from: 0,
to: '400',
speed: '3000',
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
I need that script only to run when the container div is visible.
<div class="container">
<div class="count"></div>
</div>
To clarify, the div will always be visible, but when the user scrolls it in to view. Any ideas?
http://www.windycitydigital.net/iconvert/ - Example, at the bottom of the page those counters automatically start. I don't want that script to initiate until the user scrolls into view of them.
Here is an example with the alert activated only when the #mydiv is in view:
This works as you asked. Make sure the window is small so #midiv is not in view from the beginning. And after you scroll down, after the entire #mydiv is visible it will activate the alert from the scroll event.
http://jsfiddle.net/u3eCG/7/
divScroll = $("#mydiv").offset().top + $("#mydiv").height();
$(window).scroll(function(){
lastLineScroll = $("body").scrollTop() + $(window).height();
if (divScroll < lastLineScroll) {
alert("Div is visible");
$(window).unbind("scroll");
}
});
What code shoud hide/show div?For example you can use this code to show div
$('.container').show(0, onContainerVisible);
function onContainerVisible(){
jQuery(function($) {
$('.count').countTo({
from: 0,
to: '400',
speed: '3000',
refreshInterval: 50,
onComplete: function(value) {
console.debug(this);
}
});
});
}
if your browser compatibility requirements support it... MutationObserver might be a good candidate here
https://developer.mozilla.org/en-US/docs/Web/API/MutationObserver
you could do something like this..
function isViewed(selector) {
var viewport = $(window),
item = $(selector);
var viewTop = viewport.scrollTop(),
viewBtm = viewport.scrollTop() + viewport.height(),
itemTop = item.offset().top,
itemBtm = item.offset().top + item.height();
return ((itemTop < viewBtm) && (itemTop > viewTop));
};
var counter = setInterval(function() {countdown()}, 500);
var countdown = function() {
console.log('are you there?');
if(isViewed('#mydiv')) {
clearInterval(counter);
console.log('yes i am here.'); // call countdown here
}
};
here is a jsfiddle to demonstrate
http://jsfiddle.net/pixelchemist/aLT7w/

$(window).resize() doesn't fire function

I wrote a function that's supposed to fire when the page first loads, and when a user resizes the window. It works fine when the page loads, but it doesn't work when the user resizes the window. What's weird is that if I put an alert inside the function, that alert shows up when the window gets resized, but the rest of the function doesn't fire. I'm not seeing any error's in Chrome's console. I've tried changing it to $(document).resize(), $("body").resize(), and $(".pricingHeader").resize(), and nothing's worked. This makes no sense to me.
function getTallest() {
var tallest = 0;
$(".pricingHeader").not(".features .pricingHeader").each(function(){
tallest = $(this).height() > tallest?$(this).height():tallest;
});
$(".pricingHeader").not(".features .pricingHeader").height(tallest);
$(".features .pricingHeader").height(tallest + 8);
}
$(document).ready(function() {
getTallest();
});
$(window).resize(function() {
getTallest();
});
Try :
function getTallest() {
var tallest = 0;
$(".pricingHeader").not(".features .pricingHeader").each(function(i, elem){
if ( $(elem).height() > tallest ) tallest = $(elem).height();
});
$(".pricingHeader").height(function() {
var add = $(this).closest('.features').length ? 8 : 0;
return tallest+add;
});
}
$(function() {
$(window).on('resize', getTallest).trigger('resize');
});
Alright, I figured out what the problem was. I was setting the height of every .pricingHeader to a fixed height, which was preventing the tallest from resizing on window resize. Here's the fixed script:
function getTallest() {
var tallest = 0;
$(".pricingHeader").not(".features .pricingHeader").each(function(){
$(this).css({height:"auto"});
tallest = $(this).height() > tallest?$(this).height():tallest;
});
$(".pricingHeader").each(function() {
$(".pricingHeader").not(".features .pricingHeader").height(tallest);
$(".features .pricingHeader").height(tallest + 8);
});
}
$(document).ready(function() {
getTallest();
});
$(window).resize(function() {
getTallest();
});

Why jQuery doing unwanted multiple actions of single command?

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

Categories

Resources