jQuery slide is jumpy - javascript

I tried to slide in and out a DIV with the toggle function of jQuery but the result is always jumpy at the start and/or end of the animation. Here's the js code that I use:
$(document).ready(function(){
$('#link1').click(
function() {
$('#note_1').parent().slideToggle(5000);
}
);
And the HTML:
<div class="notice">
<p>Here's some text. And more text. <span id="link1">Test1</span></p>
<div class="wrapper">
<div id="note_1">
<p>Some content</p>
<p>More blalba</p>
</div>
</div>
</div>
You can also see the complete example here: jQuery Slide test
I usually use Mootools and I can do this slide without any problems with it. But I'm starting a new project in Django and most app in Django use jQuery. So for that and after reading this jQuery vs Mootools I decided that will be a good occasion to start using jQuery. So my first need was to slide this DIV. And it didn't work properly.
I did more search and I found that's an old bug in jQuery with margin and padding applied to the DIV. The solution is to wrap the DIV in another DIV. It didn't fix the thing in my case.
Searching further I found this post Slidedown animation jumprevisited. It fix a jump at one end but not at the other (Test2 in jQuery Slide test).
On Stack Overflow I found this jQuery IE jerky slide animation. In the comments I saw that the problem is with the P tag inside the DIV. If I replace the P tags with DIV tags that fix the problem but that's not a proper solution.
Lastly I found this Weird jQuery behavior slide. Reading it I understood that the problem resolved by switching from P tag to DIV was with the margins of the P (not present in the DIV) and the collapsing of margins between elements. So if I switch the margins to paddings it fix the problem. But I loose the collapsing behavior of margins, collapsing that I want.
Honestly I can say that my first experience with jQuery is not really good. If I want to use one of the simplest effect in jQuery I have to not use the proper function (slideToggle) but instead use some hand made code AND wrap the DIV in another DIV AND switch margins to paddings, messing my layout.
Did I miss a simpler solution ?
As krdluzni suggest, I tried to write as custom script with the animate method. Here's my code:
var $div = $('#note_2').parent();
var height = $div.height();
$('#link2').click(
function () {
if ( $div.height() > 0 ) {
$div.animate({ height: 0 }, { duration: 5000 }).css('overflow', 'hidden');
} else {
$div.animate({ height : height }, { duration: 5000 });
}
return false;
});
But that doesn't work either because jQuery always set the overflow to visible at the end of the animation. So the DIV is reapearing at the end of the animation but overlaid on the rest of the content.
I tried also with UI.Slide (and Scale and Size). It works but the content below the DIV doesn't move with the animation. It only jump at the end/start of the animation to fill the gap. I don't want that.
UPDATE:
One part of the solution is to set the height of the container DIV dynamically before anything. This solve one jumping. But not the one cause by collapsing margin. Here's the code:
var parent_div = $("#note_1").parent();
parent_div.css("height", parent_div.height()+"px");
parent_div.hide();
SECOND UPDATE:
You can see the bug on the jQuery own site at this page (Example B):
Tutorials:Live Examples of jQuery
THIRD UPDATE:
Tried with jQuery 1.4, no more chance :-(

I found what works consistently is setting an invisible 1px border:
border: 1px solid transparent;
No need to fix the width or height or anything else and the animation doesn't jump. Hooray!

The solution is that sliding div must have the width set in pixels. Do not use 'auto' nor '%'. And you will have great result! The problem is in inline elements thats are in a sliding div.
but if they have width in px the height will be identical. Try it.

I've ran into this problem today. I did notice however that disabling all CSS fixed the problem. Also I knew it worked fine before so it must have been recent changes that caused the issue.
It turned out I used transitions in CSS to ease in and out of hovers.
Once these transitions were removed from the elements I was adding everything was fine.
So if you have the same issue, just add these lines to the elements you're adding:
-webkit-transition: none;
-moz-transition: none;
-o-transition: none;
-ms-transition: none;
transition: none;
(I might have abused transitions a bit by not just adding them to the elements I want to have transitions for, but using them for the entire website.)

Try removing all CSS margins from all the elements. Usually jerky animation comes from margins not being taken into account by the animation framework.

Jerking happens when the parent div ".wrapper" in your case has padding.
Padding goes on the child div, not the parent. jQuery is animating height not padding.
Example:
<div class="notice">
<p>Here's some text. And more text. <span id="link1">Test1</span></p>
<div class="wrapper" style="padding: 0">
<div id="note_1" style="padding: 20px">
<p>Some content</p>
<p>More blalba</p>
</div>
</div>
</div>
Hope this helps.

I find animate() is the most reliable way to animate anything in jQuery (cross browser at least).
This dynamically wraps the content in a div, then animates the height of that div wrapper by using the height of its inner content.
http://jsfiddle.net/BmWjy/13/
$('a').click(function(event) {
event.preventDefault();
xToggleHeight($(this).next());
});
//For each collapsible element.
$('.collapsible').each(function() {
//Wrap a div around and set to hidden.
$(this).wrap('<div style="height:0;overflow:hidden;visibility:hidden;"/>');
});
function xToggleHeight(el){
//Get the height of the content including any margins.
var contentHeight = el.children('.collapsible').outerHeight(true);
//If the element is currently expanded.
if(el.hasClass("expanded")){
//Collapse
el.removeClass("expanded")
.stop().animate({height:0},5000,
function(){
//on collapse complete
//Set to hidden so content is invisible.
$(this).css({'overflow':'hidden', 'visibility':'hidden'});
}
);
}else{
//Expand
el.addClass("expanded").css({'overflow':'', 'visibility':'visible'})
.stop().animate({height: contentHeight},5000,
function(){
//on expanded complete
//Set height to auto incase browser/content is resized afterwards.
$(this).css('height','');
}
);
}
}

You could write a custom animation using the animate method. This will give you absolute control over all details.

I noticed if you have a <br /> after your container <div> the animation will also be jumpy. Removing this resolved my problem.

css padding and jquery slideToggle doesn't work well together. Try to box out padding.

There are obviously a lot of different solutions to this issue - and depending on your layout, different solutions have different results.
Here was what I had (stripped down)
<div>
<p>Text</p>
</div>
<div class="hidden">
<p></p>
</div>
When I would use jQuery to show <div class="hidden">, the margin on the <p> element would collapse with the margin of the <p> element above it.
I thought it was strange since they were in different <divs>.
My solution was to eliminate the margin on the bottom of the <p>. Having a margin on one side prevents the margin from the bottom of the first <p> from collapsing with the top of the second <p>.
This workaround solved my problem, can probably be applied to others, but may not work for all.

You just have to modify the up, down effects in effects.js to have them take into account margins or paddings that may exist and then adjust what they perceive to be the total size of the element to accommodate those values...something along these lines....
Effect.BlindDown = function(element) {
element = $(element);
var elementDimensions = element.getDimensions();
//below*
var paddingtop = parseInt(element.getStyle('padding-top'));
var paddingbottom = parseInt(element.getStyle('padding-bottom'));
var totalPadding = paddingtop + paddingbottom;
if(totalPadding > 0)
{
elementDimensions.height = (elementDimensions.height - totalPadding);
}
//above*
return new Effect.Scale(element, 100, Object.extend({
scaleContent: false,
scaleX: false,
scaleFrom: 0,
scaleMode: {originalHeight: elementDimensions.height, originalWidth: elementDimensions.width},
restoreAfterFinish: true,
afterSetup: function(effect) {
effect.element.makeClipping().setStyle({height: '0px'}).show();
},
afterFinishInternal: function(effect) {
effect.element.undoClipping();
}
}, arguments[1] || { }));
};

Try setting the 'position' property of the the container (in this case the .notice div) to 'relative'.
Worked for me.
Source: slideToggle height is "jumping"

There are a lot of suggestions here and a lot of back and forth as to what works. For me, the behavior problem was when the animation of expanding the container would over expand and then bounce back to the correct expansion height (all done as part of the one animation). In way of example, the animation would expand to a height of 500px initially and then retract to 450px. There was no problem with collapse.
The solution that worked was to add to the expanding/collapsing div, a CSS of:
white-space: nowrap;
That worked perfectly - smooth expansion to the correct height.

I had the same issue, but not a single one of the proposed solutions worked for me, so I propose a solution that eliminates relying on slideToggle() altogether.
Spark Notes: Load the page as normal, collect the height of each element you want to toggle, store that height in a special data attribute, and then collapse each element. Then it's as easy as changing the max-height between the value in the element's data-height attribute(expanded) and zero(collapsed). If you want to add extra padding and margins, etc to the elements, I recommend storing those in a separate CSS class to add and remove with the max-height property.
Place the jQuery right after the elements you want to toggle and allow them to execute during page load (so you don't have to watch them all load and then collapse).
HTML
<ul id="foo">
<li>
<h2>Click Me 1</h2>
<div class="bar">Content To Toggle Here 1</div>
</li>
<li>
<h2>Click Me 2</h2>
<div class="bar">Content To Toggle Here 2</div>
</li>
</ul>
CSS
#foo>li>div.bar {transition: all 0.5s;
overflow: hidden;}
jQuery
$('#foo h2').each(function(){
var bar = $(this).siblings('.bar');
bar.attr('data-height', bar.height()); //figure out the height first
bar.css('max-height', '0px'); //then close vertically
});
$('#foo h2').click(function(){
var bar = $(this).siblings('.bar');
if ( bar .css('max-height') == '0px' ){ //if closed (then open)
bar.css('max-height', bar.data('height') + 'px');
} else { //must be open (so close)
bar.css('max-height', '0px');
}
});
Here is a working JSFiddle: http://jsfiddle.net/baacke/9WtvU/

The problem is that you are performing the action on the parent, doing this removes the CSS related to that element.
You need to run the slide on your note1, not the parent of note 1.
I had the same issue and fixed it by moving down a level.

For me removing the min-height from my container solved the problem.

You might try adding a doctype if you don't have one, it worked for me on IE8 after I found the suggestion here on SO: jQuery slideToggle jumps around. He suggests a strict DTD but I just used the doctype that google.com uses: <!doctype html> and it fixed my problem.

i came across the same bug took days to find a solution. the problem is when the element is hidden jquery is getting the wrong height. top fix it you must get the hight before hiding and use a custom animation to that height. its tricky go here for a better explanation

I had the same problem with 'jerkyness' with divs inside my nav tag - my aim is to show an unordered list on hover of the div (if one exists). My lists are dynamically created so they do not have a fixed value.
Heres the fix:
$("nav div").hover(
function() { // i.e. onmouseover function
/****simple lines to fix a % based height to a px based height****/
var h = jQuery(this).find("ul").height(); //find the height
jQuery(this).find("ul").css("height", h);
//set the css height value to this fixed value
/*****************************************************************/
jQuery(this).find("ul").slideDown("500");
},
function(){ // i.e. onmouseout function
jQuery(this).find("ul").slideUp("500");
});
});

Ran into this issue today, saw this question, and started tinkering based on what I saw here. I solved our jumpy issue by removing the position:relative from the CSS of the containing div. No more weirdness after that. My 2 cents.

Make sure you don't have CSS transition rules set globally or on your container or any included elements. It will also cause jerkiness.

In my case I solved it adding style="white-space:nowrap;" to the element to prevent miscalculations on the jQuery function; no need to set a fixed width unless you need to wrap.

I was using slideDown() like this
$('#content').hide().delay(500).slideDown(500);
For me, it was the main container #content element. I was having it hidden and then calling slideDown(). I removed the padding property in the CSS and everything worked fine after that. It's usually a margin, padding, or % width, so the easiest method is commenting out each property and testing them 1 by 1 to get your results.

I just learned that this problem can also occur if there are floated elements in the expanding/collapsing element. In that case, a clearfix (clear: both;) at the end (still within) the animated element can get rid of it.

I had the same issue. I fixed it by adding this:
.delay(100)
Guess giving it more time to think helps it along?

Adding my solution: turned out my issue was flexbox (only in chrome). I had align-items: baseline; set on the parent element. Set align-self: center; to my slideToggling full-width child element and it cleared it right up. Great use of two hours.

For me the solution was, that i had a CSS style definition like following:
* {
transition: all .3s;
}
Removing this was the solution!

Related

Weird flicker in jQuery toggle

I have a weird problem and i cant find a solution no matter what i tried.
I have a simple menu that toggles few divs (slide up/down), like this:
<div class="navigation">
<ul class="left">
<li>lorem1</li>
<li>lorem2</li>
<li>lorem3</li>
</ul>
</div>
and a few divs that are being toggled.Pretty simple but there is a lot of code, so i wont paste it here.
Script that makes it work is:
$('.navigation a').click(function() {
var $requested = $(this.getAttribute('href'));
$('.top-drawer').not($requested).slideUp('slow');
$requested.slideToggle('slow')
});
Once the user clicks on the link, the div slides down more than it should, flickers and then it becomes the real height (the height is should be).
Here is a Fiddle. Please be sure to have the "Result" Window at at least 1000+ px wide otherwise it wont work (the error wont be shown).
See my suggestion on this JSFIDDLE
Here an explanation of the changes in there:
The Problem
With all those floating elements inside each .top-drawer jQuery has a lot of issues calculating the height of the div because the elements will move around while sliding up and down.
Suggestion
Switching to inline-block instead. But for that to work with your CSS, particularly with the padding on each .top-drawer, you need to use box-sizing: border-box; on anything that is using padding, inline-block and width with %. If curious you can read about this HERE.
New problem
If you go the route of inline-block (best practice now). You will need to use jQuery 1.8.xx or higher. I noticed in your fiddle you use 1.7.2, which has a bug with border-box that was fixed in versions after that.
Try to understand the code you are using.
This is the way I think jQuery's slideUp(), and slideDown() works; mainly the algorithm changes the height of the element, and display after the height is equal to the height of the element or at "0".
So when you will have your element's position set to relative you will see what you're calling "flickers", specially when you have multiple element at the same position. You will also see these "flickers" when you use fadeIn(), fadeOut() etc, because the display of the element is not instantly set to "none" or anything visible in these cases, but after the animation completes.
Solution:
Set the element's position to absolute. That should solve your issue;
example.

html5: link to the #id of a div at a certain point on the page

I have a responsive header that I'm working on for a site that turns into a fixed-position navbar as you scroll down. It takes up roughly the upper quarter of the page.
The content of the page is in a series of divs / cards that slide up as you scroll down.
I want to add <a href> links to the navbar that correspond to the ids of the divs. However, when I do so, the div content moves to the top of the page.
So I get something like the following when I navegate to /localhost#first_card
---- TOP OF PAGE
[<div id="first_card"> begins here]
---- bottom border of navbar
[<div id="first_card"> continues here]
when what I really want is this:
---- TOP OF PAGE
---- bottom border of navbar
[<div id="first_card"> begins here]
Is there a way to control where on the page the hash link might render the <div id="first_card"> after navigating to /localhost#first_card?
I've been trying to solve this for you in JSFiddle for a bit now, and from what I can find, the best way would be to box all the cards into a seperate element with overflow:auto
The result of this, and as proof of it working can be found at http://jsfiddle.net/Entoarox/TT2JN/
This may not work for your site, but the only alternative is using javascript to solve this and I cant recommend that because it would cause a massive load on the visitors PC due to most hash related javascript functionality being either static or very new, meaning that to support older browsers, you'd need to manually poll if the hash has changed, either taking up a lot of CPU time, or having a very slow response to when the hash has changed.
Try the jQuery scrollTop() command. This will give you the precise positioning that you need.
http://api.jquery.com/scrollTop/
You might have to change your links up a little. Example with jQuery and a wrapper div:
<a id="first-card-jump" href="#first_card">Jump to First Card</a>
<div id="wrapper">
NAVBAR
first div
second div
...
nth div
</div>
<script>
$('a#first-card-jump).on('click', function(event) {
event.preventDefault(); // Not sure if this is needed
$('div#wrapper).scrollTop(500); // you have to measure how far down you want to scroll
});
</script>
Note that this might mess up your in-page back button support. Not sure if that's an issue for you.
p.s. If you're in time trouble, the simplest fix is to add a top margin to each div equal to the height of the fixed navbar.
Hope this helps!
I made you a jsfiddle
it uses padding-top to create the offset to the top, then it uses margin-bottom to remove the offset between the elements.
the relevant css:
/*
add top padding and substract the same amount from bottom margin
*/
.card {
padding-top: 200px;
margin-bottom: -200px;
position: relative;
}
/*
we need to reverse the stacking for this solution, so the elements later in
the document don't cover the elements before
either you know how many cards you have, so you can solve this in a central
css file (like below)
or you must add the stacking upon creation (in your template)
or use the javascript
starts from 2 because nav is :nth-child(1) in this example
*/
.card:nth-child(2){
z-index: 0;
}
.card:nth-child(3){
z-index: -1;
}
.card:nth-child(4){
z-index: -2;
}
javascript to reverse the stacking, using jQuery
$(function(){ //on load
$('body>.card').each(function(i, elem){$(elem).css('z-index', -i)})
})
If I understand your question correctly, you want to make a div appear in the middle of the page, right? So, to do this, you can just direct the page to the div above it. You can also make another div above it with a fixed height.

Odd "shaking" effect when animating width with jQuery (only in Chrome!)

I'm animating the width of a li element using jQuery in a simple snippet of code. I'm using hover() as the handler and .animate() to animate the width. Here is my code.
$('li').each(function() {
//store the original width of the element in a variable
var oldWidth = $(this).width();
$(this).hover(
function() {
//when the mouse enters the element, animate width to 900px
$(this).animate({width: '900px'}, 600, 'linear')
},
function() {
//when the mouse leaves, animate back to the original width
$(this).animate({width: oldWidth}, 350, 'linear')
}
);
});
The code is really really simple and works but with one very odd quirk in Chrome. When animating the elements in and out, the li elements "shake" as if they're really cold and were shivering. You can see the behavior here in a live example: http://missmd.org/ (edit: bug is now fixed)
I've animated a bunch of stuff before with jQuery and never seen this behavior. Is there any explanation for why it occurs and how I can get around it? I'm wondering if it's because I've floated the elements to the right and am animating to the left. The bug is maddening and detracts from the overall presentation a lot (at least to me). Anyone else seen this before?
Edit to clarify: it's not the actual li element that "shivers" it's the text within it that shakes slightly but noticeably from left to right very quickly as the animation runs. I'm stumped.
Edit two: after fiddling with the CSS a bit now I can only reproduce the effect in Chrome (21.0.1180.60 beta-m for me). In Firefox it works as intended. It also works great in IE. Very ironic that Chrome (usually great with this stuff) is giving me trouble now. Pulls hair out, checks sanity
Here is my HTML to help get to the bottom of this. We have reproduced the problem in ChrisFrancis' jsFiddle.
<nav>
<ul class="nav">
<li class="one">
<a href="homeandnews/">
<span class="title">Home and News</span>
<br/>
<span class="subtitle">Learn more about me and read general updates!</span>
</a>
</li>
</ul>
<nav>
I'm completely stumped. This could also be a bug in Chrome/V8 JS engine and there's nothing we can do about it.
I was looking to this issue as well and this: -webkit-backface-visibility: hidden; solve my problem. I add this odd shaking while using CSS3 transform on a SVG.
More info can be found here: CSS3 transform rotate causing 1px shift in Chrome
Hope it helps
I changed your css: ul.nav li a, adding float: right to it and that fix the shake.
Anyway if it helps, I had the same problem when animating height of a div within another div with height:auto. Changing the height to a fix width solved it.
Hope it helps.
This seems to be a bug in Chrome version 21.0.1180.60 and may also be present in other versions. Nothing wrong with the code here and I guess we just leave it up to workarounds or submitting a bug report now.
Sigh.
Had similar issue with shaking SVGs when there's a CSS transition applied to parent tag. I tried to apply everything I could randomly, and this fix finally helped:
svg {
transform: translate3d(0, 0, 0);
}
This problem occurred with some divs when I was trying to animate another div within it. What I noticed is that it happens if the div or element has css property display:inline-block. Making the element float would have solved the problem, but inline-block was required in my case.
I noticed that the element had also vertical-align:middle css property. Changing it to vertical-align:text-bottom solved the problem. No more shaking effect in Chrome v23 (may be the bug is still persisting in newer versions).

jquery animate from center to far left or far right (off screen based on doc width)

I have a fixed width element that I want to essentially shoot off the screen either to the left or to the right, I want it to be seen visually though hence the use of animate. However its not working out as planned with my current attempts.
What it currently seems to be doing is jumping to the opposite side of the screen then panning across in the direction I want. However what I want it to do is from where it sits go across the screen
$('.element').animate({'marginLeft':($(document).width())+'px'},1000, function(){$('#dashboardWidgetContainer').hide().html('')});
that is what I am attempting to use to achieve my desired goal
a sample of the layout would be
<div id="container">
<div class="element"></div>
</div>
set it a fixed position first
go:
$el = $('.element');
$el.css({
position: 'fixed',
top: $el.offset().top,
left: $el.offset().left
}).animate({left:'100%'}, 1000);
Are you trying to achieve something like this:
http://jsfiddle.net/t2FxV/
If it is jumping across the screen it probably has to do with margin changing from auto to 0, like in this example: http://jsfiddle.net/Paulpro/t2FxV/1/.
Make sure you set the marginLeft to the current position before animating:
$('#element').css('marginLeft', $('#element').position().left).animate({'marginLeft':($(document).width())+'px'},1000, function(){$('#container').hide().html('')});
http://jsfiddle.net/Paulpro/pakCP/
Your script works fine as jdavies pointed out (post deleted?), you might need to change the dashboardWidgetContainer to a selector for an element that exists. One thing you should note is that if you don't plan on reinserting the element into the page you should replace .hide().html('') with .remove() as it's much cleaner to remove the element from the DOM altogether than leave it sitting out there with display: none; and no contents.
$('#element').css('marginLeft', $('#element').position().left).animate({'marginLeft':($(document).width())+'px'},1000, function(){$('#container').remove()});

Problem with jerky animation in jQuery

Ive done this a number of times with no problem but for some reason it is a problem on Here. The slide down will begin to work (1/3) normally and than all of a suddenly jerk and finish the animation. slideing up works fine. this is the case for slideDown(), slideToggle and .animate()
strangely if i also toggle opacity in the animate function it does not jerk but my text will briefly change color.
HTML:
<h2>Phthalate Free: </h2><div class="yamikowebsToggler">
<p>
Dibutyl Phthalate is linked to cancer and is present in nail polish, perfume, soft plastics and skin care products.
</p></div>
CSS: i read else were that margins can cause the jerkiness but this isnt helping
h2{color:#76DEFC; margin:0px;}
.yamikowebsToggler{margin:0px;}
p{margin:0px; color;#000000;}
JQUERY:
$(document).ready(function(){
$(".yamikowebsToggler").fadeOut(0);
$("h2").click(function()
{
$(this).next(".yamikowebsToggler").stop(true, true).animate(
{ height: 'toggle' },
{
duration: 1000,
});
})
});
I found the solution. it had nothing to do with my code but a bug in jquery. jquery has trouble getting the height if it is inherited because when it is getting the height the element is hidden. when elements are hidden they are treated with css properties of
position: absolute;
visibility: hidden;
to fix this you need to specify the height in either the animation which is not doable in my case since i have many that are toggled. the alternative is to set the height to the elements. i personally added a note in my jQuery about it and did it all in line simply adding
style="height: <height in px>;"
to the elements being toggled.
I had a similar issue when animating a division from 100% down to 0% width.
What was happening was that at the start of the animation the division got wider to like 110% for some reason.
Anyway I found the solution was to add max-width: 100%; in the CSS styles on the specific division.
Just thought I'd post that here as I came here looking for a fix to this issue. :)
Have you tried increasing your {duration: ...}? Also, you could just use the built-in jQuery function .slideToggle().
I know this is marked as answer, but would like to provide an update on this issue.
The corresponding issue ticket is here:
http://bugs.jquery.com/ticket/4541
However it's been closed by core devs, and seems like it won't be fixed unless there's a patch that has no performance flaws.
In the mean time, if you still wish to use jQuery to do this, you can either set the height or the width of the element you're trying to slideUp or slideDown. It doesn't have to be in "pixel" unit, it can be in percentage as well.

Categories