Stop/Restart an animation loop on window resize - javascript

I have an animation where three images rotate up and down. JSfiddle: http://jsfiddle.net/rLgkyzgc/1/
$(window).load(function() {
// Load images in BG that have been hidden by CSS
$('.banners').show();
// Create an empty array
var banners = [];
// Fill array with banner ids
$('.banners').each(function () {
var banner = $(this).attr('id');
banners.push(banner);
});
function switchBanners(){
var $firstBanner = $('#' + banners[0]);
var $secondBanner = $('#' + banners[1]);
var firstBannerHeight = $firstBanner.height();
var secondBannerHeight = $secondBanner.height();
$firstBanner.animate({ bottom: -firstBannerHeight }, 1200);
$secondBanner.animate({ bottom: 0 }, 1200, function(){
b = banners.shift(); banners.push(b);
setTimeout(function(){
switchBanners();
}, 4000);
});
};
// Delay initial banner switch
setTimeout(function(){
switchBanners();
}, 4000);
});
This is great for the desktop view, but on mobile, I want to stop the animation and just show one static image.
So my questions. How can I :
Only start the animation on page load if the window width is > 940px
Stop (reset) the animation if the page is resized to be < 940px wide
THEN restart the animation if the page resized to be > 940px wide

You should use window.matchMedia (see the documentation) to detect the viewport size on document.ready and when the window is resized, so something like this:
function resetAnimation() {
$firstBanner.stop(true, true);
$secondBanner.stop(true, true);
if(window.matchMedia("(min-width: 940px)").matches) {
//Start the animations here
}
}
$(document).ready(function() {
resetAnimation();
}
$(window).resize(function() {
resetAnimation();
}
Note that you don't really need to stopthe animations on document.ready, but this way you have a single function to reset the animations and then restart them only if necessary, which is something you typically want to do every time you resize the browser window, regardless of the viewport size.

I'll reference these in order:
1. Only start the animation on page load if the window width is > 940px
In your window load function, grab your browser width with $(window).width(). Then check that against your 940 (leave off the "px"), and perform necessary actions.
So:
if ($(window).width() > 940){ *actions* }
2. Stop (reset) the animation if the page is resized to be < 940px wide
To do this, you'll need to use the window resize function ($(window).resize()) and check your 940 against the browser width.
So:
$(window).resize(function(){
if ($(window).width() <= 940){
*stop (reset) animation*
}
});
3. THEN restart the animation if the page resized to be > 940px wide
This logic is essentially the same as #2, just reversed:
$(window).resize(function(){
if ($(window).width() > 940){
*restart animation*
}
});

Related

Jquery function only loads after page refresh

I have roughly around 50 video thumbnails on a set page.
I would like to resize them depending on the resolution.
What I have tried was using #media query in css that did not work as expected then I moved over to this.
$(document).ready(function(event) {
var width = $(window).width();
// Change thumbnail size if browser width changes (should be in real-time)
if (width <= 1300) {
console.log(width);
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
});
After inserting that script the video thumbnail size changes but as I adjust the browser the jQuery does not load and resize the thumbnail unless the page is refreshed ?
Im not sure as to why the jQuery is not loading the script in real time as the size (browser) changes.
Languages that I am using in this project : PHP, jQuery
you need to catch window resize event with jQuery and also write your code there.
$(window).resize(function() {
var width = $(window).width();
// Change thumbnail size if browser width changes (should be in real-time)
if (width <= 1300) {
console.log(width);
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
});
To reduce code repetition you can make a function and call it in both $(window).resize() and $(document).ready()
function onResize() {
var width = $(window).width();
if (width <= 1300) {
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
}
$(document).ready(onResize);
$(window).resize(onResize);
This should work, but it would be much better if it were done with css. Would love you help you with that if you want to post what you tried. If you do it with css, you will not have the jumping on the page that'll occur when the js loads and changes those classes in and out.
You can do smth like this.
Note: this is untested code
function updateSizes(){
var width = $(window).width();
if (width <= 1300) {
$('.mdl-cell').removeClass('mdl-cell--3-col').addClass('mdl-cell--4-col');
} else {
$('.mdl-cell').removeClass('mdl-cell--4-col').addClass('mdl-cell--3-col');
}
}
$(document).ready(function(event) {
updateSizes();
// do other stuff here
});
$( window ).resize(function() {
updateSizes();
// do other stuff here
});

How to detect a browser screen width increase past a certain point using jQuery?

basically, what I want to do is trigger an event if the user increases the size of the browser from X to Y. Provided X = Anything less than 750 pixels, and Y is anything more than 750 pixels.
Right now, I am doing something like this:
$(window).resize(function(){
if ($(window).width() >= 750) {
console.log('750 or more');
}
});
This works, however, its clearly not efficient. For example, if I resize my window from 780px to max width (1024px), even then the event gets triggered. Or even if I decrease the size from 800px to 780px, I still obviously get the console output.
How do I get this to work right?
You will need to setTimeout to allow check to take place .
Example :
var resizeTimer;
$(window).resize(function() {
clearTimeout(resizeTimer);
resizeTimer = setTimeout(function() {
var body_size = $(window).width();
// ...
// do your screen check here
// ...
}, 1);
})
Hope this helps
There's no true solution for this issue since removing the on resize event after max width has been reached results in the on resize function no longer being called even when the width is below 1024px.
Maybe in the future it's possible to have an on resize event under certain conditions only.
You can also use the on resize end event to only trigger the function after resizing the window, keep in mind this might result in visual changes happening after a user has resized a window instead of during the resizing of a window.
There are multiple methods to make the on resize event perform better: http://bencentra.com/code/2015/02/27/optimizing-window-resize.html
Here is a throttled version using script that might be a good start
Fiddle demo
(function(timeout,bigger) { // local static var - timeout,bigger
window.addEventListener("resize", function(e) {
if ( !timeout ) {
timeout = setTimeout(function() {
timeout = null;
actualResizeHandler(e);
// Set the actual fire rate
}, 66);
}
}, false);
function actualResizeHandler(e) {
// handle the resize event
if (window.innerWidth >= 750 && !bigger) {
//passed above (or equal) 750
document.querySelector('span').style.color = 'blue';
document.body.innerHTML += '<br>above 750';
} else if (window.innerWidth < 750 && bigger) {
//passed below 750
document.querySelector('span').style.color = 'red';
document.body.innerHTML += '<br>below 750';
}
bigger = (window.innerWidth >= 750);
}
// run once at load
bigger = (window.innerWidth < 750);
actualResizeHandler();
}(null,false));
<span>This text is blue on big and red on small</span>
and here is one use CSS media query
span {
color: red;
}
#media screen and (min-width: 750px) {
span {
color: blue
}
}
<span>This text is blue on big and red on small</span>

Auto-scroll embedded window only once when entering viewport. Can't scroll back up

I have an image embedded in a container with a background image to give the effect of scrolling within the page. Initially, I had the scrolling effect take place on page load, with this simple bit of script which worked perfectly.
$(window).on("load", function () {
$(".embedded_scroller_image").animate({ scrollTop: $('.embedded_scroller_image')[0].scrollHeight}, 2500, "easeInOutCubic");
}); // end on load
However, the element is too far down the page now and I want that animation to fire when the element enters 80% of the viewport. That part is also working fine with this code here (I'm using a scroll limiter to improve browser performance)
// limit scroll call for performance
var scrollHandling = {
allow: true,
reallow: function() {
scrollHandling.allow = true;
},
delay: 500 //(milliseconds) adjust to the highest acceptable value
};
$(window).on('scroll', function() {
var flag = true;
if(scrollHandling.allow) { // call scroll limit
var inViewport = $(window).height()*0.8; // get 80% of viewport
$('.embedded_scroller_image').each(function() { // check each embedded scroller
var distance = $(this).offset().top - inViewport; // check when it reaches offset
if ($(window).scrollTop() >= distance && flag === true ) {
$(this).animate({ scrollTop: $(this)[0].scrollHeight}, 2500, "easeInOutCubic"); //animate embedded scroller
flag = false;
}
});
} // end scroll limit
}); // end window scroll function
The problem is this: I want the autoscroll to happen once and then stop. Right now, it works on entering viewport, but if I then try to manually scroll the image, it keeps pushing back down or stutters. You can't get the element to scroll normally. I attempted to use the flag in the code to stop the animation, but couldn't get that to successfully work.
How can I have this animation fire when the element is 80% in the viewport, but then completely stop after one time?
Here is a codepen I mocked up as well http://codepen.io/jphogan/pen/PPQwZL?editors=001 If you scroll down, you will see the image element autoscroll when it enters the viewport, but if you try to then scroll that image up in its container, it won't work.
Thanks!
I have tweaked your script a bit:
// limit scroll call for performance
var scrollHandling = {
allow: true,
reallow: function() { scrollHandling.allow = true; },
delay: 500 //(milliseconds) adjust to the highest acceptable value
};
$(window).on('scroll', function() {
if(scrollHandling.allow) { // call scroll limit
var inViewport = $(window).height()*0.8; // get 80% of viewport
$('.embedded_scroller_image').each(function() { // check each embedded scroller
var distance = $(this).offset().top - inViewport; // check when it reaches offset
if ($(window).scrollTop() >= distance ) {
$(this).animate({ scrollTop: $(this)[0].scrollHeight}, 2500, "easeInOutCubic"); //animate embedded scroller
scrollHandling.allow = false;
}
});
} // end scroll limit
}); // end window scroll function
I have kicked out your flag and simply made use of scrollHandling.allow declared already.
Try if it works for you :)
Cheers!

jQuery hover animations based on viewport size

in the process of learning more jQuery and have an issue with some code.
I am attempting to have an animation effect (fadeIn/fadeOut) when the user hovers over a specific element.
However, when the viewport is resized, ie below 480px for mobile display, I need the hover effects to be ignored and just display the call to action. In my code below I am trying to detect the viewport and then apply the appropriate script through an if-then-else statement.
I suspect that I'm not nesting something properly or have a misplaced semi-colon. I've been staring at this a while and am stuck.
I did look at these other posts as reference.
http://j.mp/1hejP0B
http://j.mp/1hejRFK
Let me know if you have any questions or can provide additional details.
// Script to display div call-to-action over logos
var detectViewPort = function(){
var viewPortWidth = $(window).width();
// if its bigger than 480px then do the hover effect
if (viewPortWidth > 480){
// On mouse over logo
$('.unionlogo').hover(function() {
// Display the call to action
$(this).find('a.calltoaction').stop(false,true).fadeIn(400);
$(this).find('p.union-name').stop(false,true).fadeOut(400);
},
function() {
// Hide the call to action
$(this).find('a.calltoaction').stop(false,true).fadeOut(400);
$(this).find('p.union-name').stop(false,true).fadeIn(400);
});
// if its smaller than 480px then just show the call-to-action
}else{
$('a.calltoaction').show();
};
$(function(){
detectViewPort();
});
$(window).resize(function () {
detectViewPort();
});
Did you look in your console to see what the error message was? As you said, you left off a bracket. You should be formatting your code a little better, and it would have been obvious.
var detectViewPort = function(){
var viewPortWidth = $(window).width();
// if its bigger than 480px then do the hover effect
if (viewPortWidth > 480){
$('a.calltoaction').hide();
// On mouse over logo
$('.unionlogo').off('mouseenter mouseleave');
$('.unionlogo').hover(function() {
// Display the call to action
$(this).find('a.calltoaction').stop(false, true).fadeIn(400);
$(this).find('p.union-name').stop(false, true).fadeOut(400);
}, function() {
// Hide the call to action
$(this).find('a.calltoaction').stop(false, true).fadeOut(400);
$(this).find('p.union-name').stop(false, true).fadeIn(400);
});
// if its smaller than 480px then just show the call-to-action
} else {
$('.unionlogo a.calltoaction').stop(false,true).fadeOut(400);
$('.unionlogo p.union-name').stop(false,true).fadeIn(400);
$('a.calltoaction').show();
// un bind the hover incase of browser resize
$('.unionlogo').off('mouseenter mouseleave');
};
}
$(function(){
$(document).ready(function(){
detectViewPort();
});
});
$(window).resize(function () {
detectViewPort();
});
Maybe try adding a media query to the CSS to hide the original button and add a call to action button when the view port is 480px or less.

Why doesn't my jQuery respond to window resize?

I'm using jQuery to add some make some elements on a page transition (via the jQuery Transit plugin) when hovered upon. Since I'm trying to design responsively, I want these transitions to only happen when the browser is a certain size or larger.
I've written the following code as an attempt to do this:
$(document).ready(function(){
var $window = $(window);
var $logo = $('.logo');
function checkWidth() {
windowsize = $window.width();
}
checkWidth();
$(window).resize(checkWidth);
if (windowsize >= 768) {
$logo.hoverIntent(
function(){
$logo.transition({
perspective: '600px',
rotateY: '-10deg'
});
},
function(){
$logo.transition({
perspective: '600px',
rotateY: '0deg'
});
}
);
}
});
If I load the page in a large browser, it works as expected--the hover effect is active. If I resize the browser, making it smaller (past the breakpoint) and refresh, then it works--the hover effect is disabled. But if I resize the window without refreshing in between, then the effect doesn't respond--it either remains disabled (if resizing from a small to a large screen) or active (if resizing from large to small).
It's a minor quirk, to be sure, but I can't exactly figure out why it's happening. As far as I can tell, when the window resizes, it should be updating the windowsize variable, which should be checked in the if statement. What am I overlooking that makes this not the case?
All checkWidth currently does is assign a value to windowsize. You need to move the code that actually reads windowsize into checkWidth.
$(document).ready(function(){
var $window = $(window);
var $logo = $('.logo');
function checkWidth() {
windowsize = $window.width();
if (windowsize >= 768) {
$logo.hoverIntent(
function(){
$logo.transition({
perspective: '600px',
rotateY: '-10deg'
});
},
function(){
$logo.transition({
perspective: '600px',
rotateY: '0deg'
});
}
);
}
}
// can trigger the resize handler instead of
// explicitly calling checkWidth()
$(window).resize(checkWidth).resize();
});

Categories