jQuery - Code running even when condition isn't met - javascript

The things here are like this (long story but I have a point)
I have a menu with buttons that look like this:
*******
***B***
*******
An when you hover it expands
*************
***Button****
*************
Now, when the screen is for mobile, no more hexagons, they stack up like normal buttons, with the complete text showing instead of having to hover to read.
my markup is as follows:
S<span class="comptxt">ervicios</span>
C<span class="comptxt">ontacto</span>
F<span class="comptxt">aq</span>
B<span class="comptxt">log</span>
And I'm using jQuery to show and hide the span tags on hover and css to handle the width of the anchor tag.
$('a.btn').hover(function() {
$(this).children('span').fadeIn(500);
$('img').css('opacity', 0.5);
}, function() {
$(this).children('span').fadeOut(200);
$('img').css('opacity', 1);
});
so fade in on hover fade out when not hover.
BUT I put this javascript on an IF conditional, if the screen resizes to mobile (i'm using 500px and below as mobile) this code shouldn't run, here is the if conditional:
$(window).resize(function() {
if ($(window).width() < '501') {
$('a.btn').hover(function() {
$(this).children('span');
$('img').css('opacity', 0.5);
}, function() {
$(this).children('span');
$('img').css('opacity', 1);
});
};
if ($(window).width() > '500') {
$('a.btn').hover(function() {
console.log($(window).width());
$(this).children('span').fadeIn(500);
$('img').css('opacity', 0.5);
}, function() {
//this part of the code runs even if the window is below 500
$(this).children('span').fadeOut(200);
$('img').css('opacity', 1);
});
};
});
It's freaking me out that the conditional doesn't met and the code still runs.
Tha problem with this is that when the buttons are normal and you hover over them after the resize, the text fades out
Other thing: when you load the page and the screen is below 500 it works as it should, no fading out. The problem arises when you resize above 500 and resize back down below 500, then the fadeout happens again.

On the resize event you never remove the previous event handler from when the window was at a larger size. You can achieve this using off():
$(window).resize(function() {
if ($(window).width() < '501') {
$('a.btn').off('hover').hover(function() {
// rest of your code...
});
};
if ($(window).width() > '500') {
$('a.btn').off('hover').hover(function() {
// rest of your code...
});
};
});
A better solution may be to instead check the size of the window within the hover handler itself as detaching/attaching events for every single pixel that the window is resized is going to end up being very slow. Try this:
$(function() {
$('a.btn').hover(function() {
var opacity = $(window).width() < 501 ? 0.5 : 1;
$('img').css('opacity', opacity);
}, function() {
var opacity = $(window).width() < 501 ? 1 : 0.5;
$('img').css('opacity', opacity);
});
});

.hover(), like .click() and other functions, are additive with jQuery.
Every time the window is resised, you bind an additional function on hover.
I mean, if the window is resized by 200 pixels, you bind the function 200 times, and it will actually be executed 200 times on hover.
It's also true when you expand the window : hover functions will continue to be bond. So, on hover, 200 "small screen" functions will be executed, and 200 "large screen" functions will be executed. This is a terrible design.
At least, you have to unbind hover() before applying a new one :
$('a.btn').unbind('mouseover mouseout').hover(

Your code does not run, because you put it inside $(window).resize. It will only run when the screen is resized, but never on hover.

Related

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!

Stop/Restart an animation loop on window resize

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

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.

vertical autoscroll on mouseover - like deviantart.com "Project giveaway" has

http://www.deviantart.com/ is vertically scrolling the content of one of their container upwards when you move your cursor over it. and on mouseleave, it scrolling back down.
You can see it in action on their main page - right now at least - in a container with the text "Project Giveaway: 100 point giveaway #4". I'm wondring how they do this?
Found this line of code trough firebug:
onmouseout="if (window.LitBox) LitBox.out(this)" onmouseover="if (window.LitBox) LitBox.hover(this, true)".
So I tried to google for "LitBox" - but didn't get any luck. All I found was lightbox and listbox...
The exact effect is what I'm looking for.
Anyone know how?
$(document).ready(function () {
if ($('.content').height() > $('.container').height()) {
$(".content").hover(function () {
animateContent("down");
}, function () {
animateContent("up");
});
}
});
function animateContent(direction) {
var animationOffset = $('.container').height() - $('.content').height();
var speed = "slow";
if (direction == 'up') {
animationOffset = 0;
speed = "fast";
}
$('.content').animate({
"marginTop": animationOffset + "px"
}, speed);
}
See in JSFiddle
my code based on this code :)
Well.. it's really not that difficult to implement with jquery or css3. With jquery, on mouseover you start running a function to scroll the div up, using animate() perhaps. Then on mouseleave you stop the animation and run another animation to scroll it back.
With css 3, you can achieve it with transitions.
You can check out http://www.w3schools.com/css3/css3_transitions.asp.

Categories