jquery animate doesn't work properly - javascript

When I use jQuery .animate() with a bootstrap progress bar to set progress percentages, it only works normal the first time I use it.
I've made a JSFiddle here: http://jsfiddle.net/43bqP/
When it just had to go to 50, it somehow first goes above 500 and then animates back to 50.
How can I fix this?

What about to calculate it into pixels? Snippet of code:
...
var stepBy = $("div.progress").width() / steps.length;
...
$("div#update div.progress div.progress-bar").animate({
width : (stepBy + (stepBy * step))
}
...
JSFiddle with full code.

The problem is due to
duration : pauseBetweenSteps / 2
and the alert() method called when all the steps have been executed, but the animation is still in act.
I'm not sure to understand why you're setting duration like this. Try leaving the default (400) by unsetting it, and add a setTimeout by 500ms around the alert("done"), to be sure the animation has ended.
Working eg. http://jsfiddle.net/eEE87/

Related

Item positioning on scroll gives a warning about asynchronous scrolling

I'm trying to position two images by changing their top margin based on the scroll position.
The margins have a max value as well.
Everything works just fine but I have a warning on the console, saying that this solution can cause a jittery scrolling effect in browsers with asynchronous scrolling.
My first question is, should I worry about this?
Also, this is literally my first few lines of javascript and I'm not sure if this solution is good enough, so any advice is appreciated.
It just looks so simple I feel like there is a catch.
I could do it by adding classes to the images and set the margins in CSS, but it would be a lot longer code I guess.
I'm trying to do this strictly with js and CSS grid, just to learn to solve problems with limited tools.
The images are in a div, which is in a grid cell.
window.addEventListener("scroll", function () {
myMargin = 0.011 * window.scrollY;
if (myMargin < 3.4) { //max margin is 3.4% for myImg1
myImg1.style.marginTop = animMargin + "%";
myImg2.style.marginTop = animMargin / 2.7 + "%"; //myImg2 moves on a different scale
} else {
myImg1.style.marginTop = "3.4%"; //when the max value reached the margin is fixed
myImg2.style.marginTop = "1.25%";
}
});
Scrolling handlers can be intensive and put performance strain on the page as they will fire far more times than your handler actually needs. This ends up causing choppy/lag when scrolling as the browser may need to repaint in response to your handler.
A common technique is to throttle or debouce the handler.
Throttle:
only invokes func at most once per every x milliseconds.
Debouce:
delays invoking func until after x milliseconds have elapsed since the last time the debounced function was invoked.
The warning you are getting is actually fine, but you may benefit from using a throttled callback and increase the wait time to the max that is suitable for your needs - so least times it is called in order for it to work for you.
Demo using lodash throttle
// only call the handler once every 200ms
const throttledScroll = _.throttle(() => {
console.info('throttled', window.scrollY);
}, 200);
window.addEventListener('scroll', throttledScroll);
html,
body {
height: 300vh;
}
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>

jquery animation moving and stopping

I got a div with an image inside it using query
$('#super').animate({
left:'150px'
}, {
duration: 10000,});
What iam trying to figure out is how to stop and start animation. So for example it will start to move left 150px and then will stop for 2 seconds and then move left 300px.
Like this:
$('#super').animate({left : '-=150'}).delay(2000).animate({left : '-=300'});
Demo: http://jsfiddle.net/E7akr/
(You can add duration, easing and complete settings to the .animate() calls as desired - obviously the key thing here is the .delay() method.)

jQueryui animation with inital undefined height

See the following fiddle:
[edit: updated fiddle => http://jsfiddle.net/NYZf8/5/ ]
http://jsfiddle.net/NYZf8/1/ (view in different screen sizes, so that ideally the image fits inside the %-width layouted div)
The image should start the animation from the position where it correctly appears after the animation is done.
I don't understand why the first call to setMargin() sets a negative margin even though the logged height for container div and img are the very same ones, that after the jqueryui show() call set the image where I would want it (from the start on). My guess is that somehow the image height is 0/undefined after all, even though it logs fine :?
js:
console.log('img: ' + $('img').height());
console.log('div: ' + $('div').height());
$('img').show('blind', 1500, setMargin);
function setMargin() {
var marginTop =
( $('img').closest('div').height() - $('img').height() ) / 2;
console.log('marginTop: ' + marginTop);
$('img').css('marginTop', marginTop + 'px');
}
setMargin();
Interesting problem...after playing around with your code for a while (latest update), I saw that the blind animation was not actually firing in my browser (I'm testing on Chrome, and maybe it was firing but I wasn't seeing it as the image was never hidden in the first place), so I tried moving it inside the binded load function:
$('img').bind('load', function() {
...
$(this).show('blind', 500);
});
Now that it was animating, it seemed to 'snap' or 'jump' after the animation was complete, and also seemed to appear with an incorrect margin. This smacks of jQuery not being able to correctly calculate the dimensions of something that hadn't been displayed on the screen yet. On top of that, blind seems to need more explicit dimensions to operate correctly. So therein lies the problem: how to calculate elements' rendered dimensions before they've actually appeared on the screen?
One way to do this is to fade in the element whose dimensions you're trying to calculate very slightly - not enough to see yet - do some calculations, then hide it again and prep it for the appearance animation. You can achieve this with jQuery using the fadeTo function:
$('img').bind('load', function() {
$(this).fadeTo(0, 0.01, function() {
// do calculations...
}
}
You would need to work out dimensions, apply them with the css() function, blind the image in and then reset the image styles back to their original states, all thanks to a blind animation that needs these dimensions explicitly. I would also recommend using classes in the css to help you manage things a little better. Here's a detailed working example: jsfiddle working example
Not the most elegant way of doing things, but it's a start. There are a lot more easier ways to achieve seemingly better results, and I guess I just want to know why you're looking to do image blinds and explicit alignment this way? It's just a lot more challenging achieving it with the code you used...anyways, hope this helps! :)

How do smooth slides work in javascript?

For a while now i have been trying to figure out the algorithms behind smooth slides, fades etc..in javascript. Just to give you an example of what am talking about, I have seen a div with content in it that had a height of 0px and on toggled, it didn't just snap to height, it smoothly and gradually grew to height using some sort of function. What i do know is that the height of this div was being assigned its height value from either a date object that had an interval set or a loop of some sort. I've searched all over the web trying to find tutorials explaining how this works but failed. Can someone please either explain to me how to create my own smooth fades, slides or reference some links that i can read?
PS: I know i can just use jquery, but i want to know how the fades and slides actually work.
It's quite simple actually. All of these animations use a timer (see setInterval) with a short interval, say 100 milliseconds, and every time the timer fires, the property (height or whatever) is changed by a fraction of the total amount instead of all at once.
For example, if you want to slide from a height of 0px to 200px in 1 second, then you could set up a timer that fires every 100 ms and increases the height of the DIV by 20px. That way, in 1 second, the timer would have fired 10 times and the height would be 200px.
A simple example:
function slideOpen(elem, finalHeight, slideTime) {
var count = slideTime * 10; // 10 intervals per second
height = 0, // current height
delta = finalHeight / count; // change in height per interval
var timerId = setInterval(slide, 100);
function slide() {
height += delta;
elem.style.height = height + 'px';
if (--count == 0)
clearInterval(timerId);
}
}
I have never looked at the jQuery code myself, but i'm pretty sure it uses a loop/timeout to increment the top/left/bottom/right css position of the element gradually using the specified easing equation.
You might want to have a look at jQuery source code for the animate() function.
CSS3 makes it trivial.
For non-CSS3 based solution, this is the first Google result for the query "javascript smooth animation": http://www.schillmania.com/content/projects/javascript-animation-2/
I am adding some code from one of my projects to move the div right
belolw xs_tuck() will be called till finalleftpositionval reaches
This code makes the div move to right.
if(xs_endpt<finalLeftPositionVal){
xs_endpt+=5;
xs_pDiv2.style.left=xs_endpt;
setTimeout("xs_tuck();",20);
}

jQuery div autoscroll

I am looking for advice on how to create an autoscrolling effect using jQuery which would enable an entire div within a page to begin scrolling vertically upon loading at a constant slow speed. This would be a div with a large amount of content of which only a small amount was visible on the screen at any one time.
The scroll needs to be automatic, smooth and at a defined rate for example 10 pixels per second. Additionally when the scroll gets to the bottom of the page I need to be able to call a function.
I have tried a few different jQuery plugins but found nothing yet that worked reliably. Can anybody suggest an approach to take here?
Thanks
Simon
This can easily be done without jquery.
function init() {
var div = document.getElementById("myDiv");
// increase the scroll position by 10 px every 10th of a second
setInterval(function() {
// make sure it's not at the bottom
if (div.scrollTop < div.scrollHeight - div.clientHeight)
div.scrollTop += 10; // move down
}, 100); // 100 milliseconds
}
Try this technique
try this plugin : scrollTo
especially the onAfter

Categories