Complete function before starting next (fadeIn/fadeOut) - javascript

UPDATED (see notes at bottom)
I have created an image map and when you hover over a specific section of this image map a description will appear in a designated area (the sidebar) of my website.
Each description is of varying length therefore I have not set any maximum height level for my sidebar area so that the display can grow vertically to accomodate each description.
The problem I am having is that when you rapidly hover over areas of the image map the display produces some weird results; showing blocks up content from another hot spot for a split second in full beneath the newly hovered over area and corresponding description (hope that makes sense)
Is there anyway to complete one function in full before displaying the next to avoid this nasty display/animation?
Here is my code:
$(document).ready(function() {
$("#a-hover").hide();
$("#a").hover(function() {
$("#a-hover").fadeIn();
}).mouseleave(function() {
$("#a-hover").fadeOut();
});
$("#b-hover").hide();
$("#b").hover(function() {
$("#b-hover").fadeIn();
}).mouseleave(function() {
$("#b-hover").fadeOut();
});
$("#c-hover").hide();
$("#c").hover(function() {
$("#c-hover").fadeIn();
}).mouseleave(function() {
$("#c-hover").fadeOut();
});
And my CSS;
#a-hover,#b-hover,#c-hover {
z-index: 2;
float: left;
position: relative;
}
#a-hover,#b-hover,#c-hover,{
position: relative;
top: 0px;
left: 0px;
z-index: 1;
width:326px;
min-height:603px;
background-color:#dedddd;
}
I have shortened my code for readability (I have 9 image map hot spots)
I am a novice when it comes to jQuery but I am making a committment to learn so please go easy as my code may not be up to scratch!
I have tried to solve this myself before posting here, but I am out of my depth and need some expert advice
I appreciate any responses.
Thank You,
Wp.
UPDTAE: I tried the majority of what was provided here as answers and whilst I believe these answers are on the right track I couldn't get the problem to stop however I did notice improvement in the animations overall.
I ended up using a combination .stop(true,true); and **resize font automatically.
**Ultimately not getting the desired result is due to my lack of polish with jQuery but being in a rush I managed to find another way to handle this issue (auto resizable font).****
Thanks to all who took the time out to answer and for those reading this for a similar solution at least know the .stop(true,true); properties did in fact work for me to solve one part of this problem.

Try adding .stop before each fadeIn and fadeOut. You should pass true, true to stop to complete the animating instantly rather than leave it half faded in:
$("#a").hover(function() {
$("#a-hover").stop(true, true).fadeIn();
}).mouseleave(function() {
$("#a-hover").stop(true, true).fadeOut();
});
You can also get rid of all of the repetition by binding on a class instead of id's:
$(".imageMapElement").hover(function() {
$("#" + $(this).attr("id") + "-hover").stop(true, true).fadeIn();
}).mouseleave(function() {
$("#" + $(this).attr("id") + "-hover").stop(true, true).fadeOut();
});

May be you can try Jquery Hover Intent plugin.

try stopping the other functions:
$("#a").hover(function() {
$("#b-hover").stop().hide();
$("#c-hover").stop().hide();
$("#a-hover").fadeIn();
}).mouseleave(function() {
$("#a-hover").fadeOut();
});

Try adding .stop() before each .fadeIn and .fadeOut -- that will cancel any previous animations and immediately begin your new one.
You also have a problem with using .hover() -- that actually encapsulates two actions, mouseover and mouseout. When you assign two functions to it, the first is mouseover and the second is mouseout, but when you assign only one function to it, that one function is used for both mouseover and mouseout. So, in effect, your code is causing the element to fadeIn and fadeOut on mouseout.
Incidentally, you can shorten your code a lot using standard jQuery techniques:
$("#a-hover,#b-hover,#c-hover").hide().hover(function() {
$(this).stop().fadeIn();
}, function() {
$(this).stop().fadeOut();
});
...or even better yet, assign a class to each of those three IDs and select it instead.

You have to chain all the jQuery function calls!

Related

Creating a sliding image gallery that does not glitch on image change

I have created a sliding image gallery and when the button is pushed it slides the picture across and updates the image attribute for the relevant sections.
However this works perfectly like 50% of the time. The other times there is a second glitch and the images then go in place as expected.
I have attached the javascript methods for the animate method and the array change method. I have looked elsewhere and cannot see anyone else with a similar issue or where I am going wrong, especially when it doesn't happen often.
imageGallery.leftSelect.onclick = function () {
window.setTimeout(imageGallery.rightClick, 250);
imageGallery.animateImages('.image1', '.imageRight');
imageGallery.animateImages('.imageRight', '.imageNoneRight');
imageGallery.animateImages('.imageLeft', '.image1');
imageGallery.animateImages('.imageNoneLeft', '.imageLeft');
};
animateImages: function (classFrom, classTo) {
var classMoving = $(classFrom);
var classGoingTo = $(classTo);
classMoving.animate({
top: classGoingTo.css('top'),
left: classGoingTo.css('left'),
width: classGoingTo.css('width'),
opacity: classGoingTo.css('opacity'),
}, 258, function () {
console.log('Animated');
classMoving.css({"width":'', "opacity":'', "top":'', "left":'', });
});
},
rightClick: function () {
imageGallery.imagesDisplay.push(imageGallery.imagesDisplay.shift());
imageGallery.imageNoneLeft.setAttribute('src', imageGallery.imagesDisplay[2]);
imageGallery.imageLeft.setAttribute('src', imageGallery.imagesDisplay[1]);
imageGallery.imageMain.setAttribute('src', imageGallery.imagesDisplay[0]);
imageGallery.imageRight.setAttribute('src', imageGallery.imagesDisplay[10]);
imageGallery.imageNoneRight.setAttribute('src', imageGallery.imagesDisplay[9]);
},
Can someone assist, I really need this to work?
If there is anything not clear or you need more code let me know.
Thanks,
First things first, the culprit was the setAttribute of all images i.e. whatever you were doing inside the rightClick and leftClick functions were the reasons why you were seeing a glitch. Changing src of an img tag produces the glitch.
But then we cannot simply remove it because your approach relies heavily on this swapping of images.
I had to breakdown and really understand your approach first. The way it worked was that you would animate, for example, image1 (the centered one) to move to the position of imageLeft upon click on the rightCarousel button. On that same click, you had a setTimeout of almost the duration of the animation to call rightClick function. This rightClick function then swaps the images so that image1 can always remain at the center and only images can come and go after animation. This was the problem.
What I had to change was that all image tags i.e. imageNoneLeft, imageLeft, image1, imageRight & imageNoneRight would change each others classes such that their position remains changed after animations.
Also, I had to add another animateImages line inside your leftSelect and rightSelect callbacks to animate the furthest images i.e. imageNoneLeft & imageNoneRight to animate to each other's positions with respect to the click of the buttons.
Take a look at this jsFiddle. It will help you understand a lot better. And let me know if you have any questions.
JavaScript:
var imageGallery={
prefix:'https://dl.dropboxusercontent.com/u/45891870/Experiments/StackOverflow/1.5/',
imagesDisplay:['JS.jpg','PIXI.jpg','GSAP.jpg','JS.jpg','PIXI.jpg','GSAP.jpg','JS.jpg','PIXI.jpg','GSAP.jpg','JS.jpg','PIXI.jpg'],
rightSelect:document.querySelector('.rightCarousel'),
leftSelect:document.querySelector('.leftCarousel'),
imageMain:document.querySelector('.image1'),
imageLeft:document.querySelector('.imageLeft'),
imageRight:document.querySelector('.imageRight'),
imageNoneLeft:document.querySelector('.imageNoneLeft'),
imageNoneRight:document.querySelector('.imageNoneRight'),
init:function(){
imageGallery.imagesDisplay.push(imageGallery.imagesDisplay.shift());
imageGallery.imageNoneLeft.setAttribute('src',imageGallery.prefix+imageGallery.imagesDisplay[2]);
imageGallery.imageLeft.setAttribute('src',imageGallery.prefix+imageGallery.imagesDisplay[1]);
imageGallery.imageMain.setAttribute('src',imageGallery.prefix+imageGallery.imagesDisplay[0]);
imageGallery.imageRight.setAttribute('src',imageGallery.prefix+imageGallery.imagesDisplay[10]);
imageGallery.imageNoneRight.setAttribute('src',imageGallery.prefix+imageGallery.imagesDisplay[9]);
},
animateImages:function(classFrom,classTo){
var classMoving=$(classFrom);
var classGoingTo=$(classTo);
classMoving.animate({
top:classGoingTo.css('top'),
left:classGoingTo.css('left'),
width:classGoingTo.css('width'),
opacity:classGoingTo.css('opacity')
},258,function(){
$(this).removeClass(classFrom.substr(1));
$(this).addClass(classTo.substr(1));
$(this).removeAttr('style');
});
}
};
imageGallery.init();
imageGallery.leftSelect.onclick=function(){
imageGallery.animateImages('.imageNoneRight','.imageNoneLeft');
imageGallery.animateImages('.imageRight','.imageNoneRight');
imageGallery.animateImages('.image1','.imageRight');
imageGallery.animateImages('.imageLeft','.image1');
imageGallery.animateImages('.imageNoneLeft','.imageLeft');
};
imageGallery.rightSelect.onclick=function(){
imageGallery.animateImages('.imageNoneLeft','.imageNoneRight');
imageGallery.animateImages('.imageLeft','.imageNoneLeft');
imageGallery.animateImages('.image1','.imageLeft');
imageGallery.animateImages('.imageRight','.image1');
imageGallery.animateImages('.imageNoneRight','.imageRight');
};

MooTools Tween Stutter/Hiccup

I am doing a rather simple Tween animation using MooTools. The opening animation is perfectly smooth. But then I added the closing animation (opposite of the opening animation), but it seems to stutter/hiccup at the end almost every time.
I tried the following with no success:
Removed all HTML content from the expanding DIV
Passing the Bounce settings directly to the Set function instead of using the variable
Commented the #content animation to be sure there is only 1 animation running
Commented the addClass and removeClass actions
I can't figure out what's causing the problem. Maybe someone else can have a look…
I put the test-case online here: http://dev.dvrs.eu/mootools/
window.addEvent('domready', function() {
// Set initial Div heights
$('sideBar').setStyle('height', window.getSize().y);
$('sideMenu').setStyle('height', window.getSize().y);
// Set Div heights on Window resize
window.addEvent('resize', function() {
$('sideBar').setStyle('height', window.getSize().y);
$('sideMenu').setStyle('height', window.getSize().y);
});
var bounce = {
transition: Fx.Transitions.Back.easeOut,
duration: 500
};
$$('.button.closeMenu').addEvent('click', function(event) {
event.preventDefault();
$$('.button').removeClass('active');
this.addClass('active');
$('sideMenu').set('tween', bounce);
$('sideMenu').tween('width', 0);
$('content').set('tween', bounce);
$('content').tween('margin-left', 90);
});
$$('.button.menu').addEvent('click', function(event) {
event.preventDefault();
$$('.button').removeClass('active');
this.addClass('active');
$('sideMenu').set('tween', bounce);
$('sideMenu').tween('width', 300);
$('content').set('tween', bounce);
$('content').tween('margin-left', 390);
});
});
Fiddle with example here
The transition you are using goes over the values defined as final value in the .set(property, value);. So when opening the final width is 300px but the transition/effect goes over that and than soft back to the final value.
This works great when opening because width can be 310px or more and then return to 300px, but when with has a transition under the with 0px, it doesn't work so good. It actually works ok if the final width is 10px (check here), but that's not the effect you want.
So my suggestion is to fix it with CSS, or change the transition when closing the sidebar, or use another effect altogether.
Option 1: fiddle - same transition opening, no easeout closing
Option 2: fiddle - same effect as you have but played with CSS and hidded 10px of the sidemenu under the sidebar. (z-index:3; on #sideBar and left:80px;width: 10px; on #sideMenu. Also 10px as the final value for the tween.)
To check different transitions at Mootools demo's look here.

Jquery content filter fading effect

I wrote a little jquery content filter:
jsfiddle.
If I switch between "gfx" and "coding" for example I get this ugly height reseizing effect on the red parent div.
My goal is fading the little divs out then in, at the same place. Without any resizing and without using a fixed height. (Number of items can differ later)
Any hints how I can achieve this?
var filter = $(this).attr('data-filter');
$('#filter_container .filteritem:not(' + filter + ')').fadeOut('slow', function () {
$('#filter_container ' + filter + '').fadeIn('fast');
});
For details and working example see the jsfiddle.
http://jsfiddle.net/k6BPs/8/
The fadeOut() callback is apparently called for each element. See here. That way it will be triggered right away preventing a nice fadeIn() effect after the fadeOut().
You can overcome this problem by using the .promise() and .done(function(){}) methods though.

How do I stop a bouncy JQuery animation?

In a webapp I'm working on, I want to create some slider divs that will move up and down with mouseover & mouseout (respectively.) I currently have it implemented with JQuery's hover() function, by using animate() and reducing/increasing it's top css value as needed. This works fairly well, actually.
The problem is that it tends to get stuck. If you move the mouse over it (especially near the bottom), and quickly remove it, it will slide up & down continuously and won't stop until it's completed 3-5 cycles. To me, it seems that the issue might have to do with one animation starting before another is done (e.g. the two are trying to run, so they slide back and forth.)
Okay, now for the code. Here's the basic JQuery that I'm using:
$('.slider').hover(
/* mouseover */
function(){
$(this).animate({
top : '-=120'
}, 300);
},
/* mouseout*/
function(){
$(this).animate({
top : '+=120'
}, 300);
}
);
I've also recreated the behavior in a JSFiddle.
Any ideas on what's going on? :)
==EDIT== UPDATED JSFiddle
It isn't perfect, but adding .stop(true,true) will prevent most of what you are seeing.
http://jsfiddle.net/W5EsJ/18/
If you hover from bottom up quickly, it will still flicker because you are moving your mouse out of the div causing the mouseout event to fire, animating the div back down.
You can lessen the flicker by reducing the delay, however it will still be present until the delay is 0 (no animation)
Update
I thought about it and realized that there is an obvious solution to this. Hoverintent-like functionality!
http://jsfiddle.net/W5EsJ/20/
$(document).ready(function() {
var timer;
$('.slider').hover(
/* mouseover */
function(){
var self = this;
timer = setTimeout(function(){
$(self).stop(true,true).animate({
top : '-=120'
}, 300).addClass('visible');
},150)
},
/* mouseout*/
function(){
clearTimeout(timer);
$(this).filter(".visible").stop(true,true).animate({
top : '+=120'
}, 300).removeClass("visible");
}
);
});
You could use .stop() and also use the outer container position
$(document).ready(function() {
$('.slider').hover(
/* mouseover */
function(){
$(this).stop().animate({
top : $('.outer').position().top
}, 300);
},
/* mouseout*/
function(){
$(this).stop().animate({
top : $('.outer').position().top + 120
}, 300);
}
);
});
​
DEMO
Hope this helps
Couldn't reproduce your issue but I believe that hover is getting called multiple times. To work around this you can check if the div is already in animation. If yes, then don't run another animation again.
Add following piece of code to check if the div is already 'animating':
if ($(this).is(':animated')) {
return;
}
Code: http://jsfiddle.net/W5EsJ/2/
Reference:http://api.jquery.com/animated-selector/
I understand the problem and reproduced it, it happens when hovering from the bottom up. The hovering with the mouse is what's causing the problem since the animation function will be called when the mouse hovers over the image. You need to control what happens here by using mouse enter and mouse leave, check out a similar example: Jquery Animate on Hover
The reason it's like that is because the hover is getting queued up causing it to slide up and down multiple times. There's a plug-in called hoverIntent which fixes the issue. http://cherne.net/brian/resources/jquery.hoverIntent.html
If you do decide to use hoverIntent, the only thing you have to change in your code is .hover > .hoverIntent

Flot graph does not render when parent container is hidden

I was having an issue where a flot graph would not render in a tabbed interface because the placeholder divs were children of divs with 'display: none'. The axes would be displayed, but no graph content.
I wrote the javascript function below as a wrapper for the plot function in order to solve this issue. It might be useful for others doing something similar.
function safePlot(placeholderDiv, data, options){
// Move the graph place holder to the hidden loader
// div to render
var parentContainer = placeholderDiv.parent();
$('#graphLoaderDiv').append(placeholderDiv);
// Render the graph
$.plot(placeholderDiv, data, options);
// Move the graph back to it's original parent
// container
parentContainer.append(placeholderDiv);
}
Here is the CSS for the graph loader div which can be placed
anywhere on the page.
#graphLoaderDiv{
visibility: hidden;
position: absolute;
top: 0px;
left: 0px;
width: 500px;
height: 150px;
}
Perhaps this is better solution. It can be used as a drop in replacement for $.plot():
var fplot = function(e,data,options){
var jqParent, jqHidden;
if (e.offsetWidth <=0 || e.offetHeight <=0){
// lets attempt to compensate for an ancestor with display:none
jqParent = $(e).parent();
jqHidden = $("<div style='visibility:hidden'></div>");
$('body').append(jqHidden);
jqHidden.append(e);
}
var plot=$.plot(e,data,options);
// if we moved it above, lets put it back
if (jqParent){
jqParent.append(e);
jqHidden.remove();
}
return plot;
};
Then just take your call to $.plot() and change it to fplot()
The only thing that works without any CSS trick is to load the plot 1 second after like this:
$('#myTab a[href="#tabname"]').on("click", function() {
setTimeout(function() {
$.plot($(divChartArea), data, options);
}, 1000);
});
or for older jquery
$('#myTab a[href="#tabname"]').click (function() {
setTimeout(function() {
$.plot($(divChartArea), data, options);
}, 1000);
});
The above example is applied to Bootstrap tags for Click funtion. But should work for any hidden div or object.
Working example: http://topg.org/server-desteria-factions-levels-classes-tokens-id388539
Just click the "Players" tab and you'll see the above example in action.
This one is a FAQ:
Your #graphLoaderDiv must have a width and height, and unfortunately, invisible divs do not have them. Instead, make it visible, but set its left to -10000px. Then once you are ready to show it, just set it's left to 0px (or whatever).
OK, I understand better now what you're actually saying... I still think your answer is too complicated though. I just tried this out using a tabbed interface where the graph is in a hidden tab when it's loaded. It seems to work fine for me.
http://jsfiddle.net/ryleyb/dB8UZ/
I didn't have the visibility:hidden bit in there, but it didn't seem necessary...
You could also have visibility:hidden set and then change the tabs code to something like this:
$('#tabs').tabs({
show: function(e,ui){
if (ui.index != 2) { return; }
$('#graphLoaderDiv').css('visibility','visible');
}
});
But given the information provided, none of that seems particularly necessary.
I know this is a bit old but you can also try using the Resize plugin for Flot.
http://benalman.com/projects/jquery-resize-plugin/
It is not perfect because you'll sometimes get a flash of the non-sized graph which may be shrunk. Also some formatting and positioning may be off depending on the type of graph that you are using.

Categories

Resources