Animation example behaves erratically - javascript

I'm a beginner so I often use w3schools examples. They have the advantage of offering complete code, from html to /html. But this one failed.
I tried to use the example below to implement a game for young kids.
https://www.w3schools.com/js/tryit.asp?filename=tryjs_dom_animate_3
In my game, the user has to click on the correct location before the dropping object (a red square in this example) reaches the bottom.
Repeatedly clicking on the button produces erratic behaviour. At first the red square goes back up, but then sometimes it doesn't, and sometimes it reaches the bottom and bounces back up. If you click on it several times, quite fast, you will see what I mean.
I'm using Mozilla Firefox to test the game.
I think the problem comes from the fact that the code is interpreted in a non-linear fashion. I tried using while(1) with a break, I tried using global variables and testing each time before the move instruction as in :
if (finished == 1) return;
It's as if there was a thread somewhere who suddenly thought "Hey, I was moving this thing downwards. Let's send it up again halfway up the screen so I can finish bringing it down". And which does so even if "finish = 1".
I tried using timers as in :
setTimeout(function () {
if (finished == 1) return;
}, 100);
Nothing helped. I haven't tried to save the current state of the game in a bunch of cookies and to reload the page. Maybe I should do that, but isn't there a better way?

Here I made timer id global and clear it before starting again. In other words I stop the previous animation and start a new one.
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: yellow;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body>
<p><button onclick="myMove()">Click Me</button></p>
<div id ="container">
<div id ="animate"></div>
</div>
<script>
var id = null;
function myMove() {
var elem = document.getElementById("animate");
var pos = 0;
clearInterval(id);
id = setInterval(frame, 5);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
</script>
</body>
</html>

Related

Scroll horizontal scroll bar automatically from left to right [duplicate]

I thought this would be fairly easy but I'm stuck.
My code is executing and ignoring the setTimeout.
I am getting the scroll width of my element, then saying while i is less than the width (flavoursScrollWidth), move the horizontal scroll 1px along every second.
That isn't what is happening though, it just executes each pixel movement almost instantly.
I also tried taking the code out of the load event and taking the setTimeout out of the while loop. Then creating a function containing the while loop, and calling the function in a setInterval. Didn't help.
const flavoursContainer = document.getElementById("flavoursContainer")
const flavoursScrollWidth = flavoursContainer.scrollWidth
window.addEventListener("load", () => {
let i = 0
while (i < flavoursScrollWidth) {
setTimeout(flavoursContainer.scrollTo(i, 0), 1000)
console.log(i)
i++;
}
})
.container {
width:300px;
overflow-x:scroll;
white-space: nowrap;
}
<div class="container" id="flavoursContainer">
This is a really long sentence to demo my code, it's just going on and on. Still going. I should have used some default placeholder text but I've started now so I'll keep going.
</div>
I would suggest using setInterval rather than setTimeout and just checking if the container is scrolled to the end. I also found that if you scroll faster, like every 15ms, you get a smoother user experience.
const flavoursContainer = document.getElementById('flavoursContainer');
const flavoursScrollWidth = flavoursContainer.scrollWidth;
window.addEventListener('load', () => {
self.setInterval(() => {
if (flavoursContainer.scrollLeft !== flavoursScrollWidth) {
flavoursContainer.scrollTo(flavoursContainer.scrollLeft + 1, 0);
}
}, 15);
});
.container {
width: 300px;
overflow-x: scroll;
white-space: nowrap;
background-color: #fff;
}
<div class="container" id="flavoursContainer">
This is a really long sentence to demo my code, it's just going on and on. Still going. I should have used some default placeholder text but I've started now so I'll keep going.
</div>

Performance Problems with JS postMessage to adjust parent iframe scrollHeight

I have a file browser application I want to integrate into an iframe of a main website.
To adjust the scroll height of the iframte to the content I use following code:
iframecontent:
window.top.postMessage({ height: document.body.scrollHeight }, "*");
main site html:
<iframe id="iframe1" src="https://mysubfilebrowser.com" frameborder="0" scrolling="no" width="100%" height="10000">
Your browser doesn't support iframes
</iframe>
<script>
let iframe = document.getElementById("iframe1");
window.addEventListener('message', function(e) {
let message = e.data;
iframe.style.height = message.height + 'px';
} , false);
</script>
This works as it should but I have problems with performance. If I click in file/folder tree to fast, the post message event seems to be fired so much, that the iframe suddenly do not show the correct content or even empty areas.
Any hints what I can do, to solve this problem?
Thanks in advance!
Best regards
Mini25
It sounds like a "single" change makes that call run many times (the scroll and resize events can be like that, amongst others). To handle that, you can "debounce" your call to postMessage so it only makes the call once when it gets a lot of triggers in a short period of time.
It's quite simple to do: don't do the call right away, wait up to (say) 10, 50, or 100ms before doing it, and if you get another trigger to do it, reset that delay. That means you won't actually do it until things have settled down.
Here's a simple ad hoc version just for that code, but a web search for "debounce" will turn up various general-purpose debouncing wrappers for functions:
let updateWindowDebounceTimer = 0;
function updateWindow() {
// If there's a pending previous call, cancel it
clearTimeout(updateWindowDebounceTimer);
// Schedule a call for 10ms from now
updateWindowDebounceTimer = setTimeout(sendUpdate, 100);
}
function sendUpdate() {
updateWindowDebounceTimer = 0;
window.top.postMessage({ height: document.body.scrollHeight }, "*");
}
Then use updateWindow(); where you're currently using window.top.postMessage(/*...*/).
Here's an example using the scroll event without debouncing (notice how fast the counter goes up when you scroll):
function updateWindow() {
/*
window.top.postMessage({ height: document.body.scrollHeight }, "*");
*/
const display = document.getElementById("counter");
display.textContent = String(parseInt(display.textContent, 10) + 1);
}
window.addEventListener("scroll", updateWindow);
body {
padding-top: 0;
margin-top: 0;
}
#counter {
position: sticky;
top: 0;
}
.tall {
margin-top: 1em;
height: 10000px;
}
<div id="counter">0</div>
<div class="tall">Scroll over this div</div>
And here's an example with debouncing (notice how much more slowly the counter goes up, indicating fewer update calls):
let updateWindowDebounceTimer = 0;
function updateWindow() {
// If there's a pending previous call, cancel it
clearTimeout(updateWindowDebounceTimer);
// Schedule a call for 10ms from now
updateWindowDebounceTimer = setTimeout(sendUpdate, 50);
}
function sendUpdate() {
updateWindowDebounceTimer = 0;
/*
window.top.postMessage({ height: document.body.scrollHeight }, "*");
*/
const display = document.getElementById("counter");
display.textContent = String(parseInt(display.textContent, 10) + 1);
}
window.addEventListener("scroll", updateWindow);
body {
padding-top: 0;
margin-top: 0;
}
#counter {
position: sticky;
top: 0;
}
.tall {
margin-top: 1em;
height: 10000px;
}
<div id="counter">0</div>
<div class="tall">Scroll over this div</div>
That's an ad-hoc version, but a web search for "debounce" will turn up various general-purpose debouncing wrappers for functions.

Changing an HTML element's style in JavaScript with its CSS transition temporarily disabled isn't reliably functioning [duplicate]

This question already has answers here:
How can I force WebKit to redraw/repaint to propagate style changes?
(33 answers)
Closed 4 years ago.
Currently I am working on an animation for a website which involves two elements having their position changed over a period of time and usually reset to their initial position. Only one element will be visible at a time and everything ought to run as smoothly as possible.
Before you ask, a CSS-only solution is not possible as it is dynamically generated and must be synchronised. For the sake of this question, I will be using a very simplified version which simply consists of a box moving to the right. I shall be referring only to this latter example unless explicitly stated for the remainder of this question to keep things simple.
Anyway, the movement is handled by the CSS transition property being set so that the browser can do the heavy lifting for that. This transition must then be done away with in order to reset the element's position in an instant. The obvious way of doing so would be to do just that then reapply transition when it needs to get moving again, which is also right away. However, this isn't working. Not quite. I'll explain.
Take a look at the JavaScript at the end of this question or in the linked JSFiddle and you can see that is what I'm doing, but setTimeout is adding a delay of 25ms in between. The reason for this is (and it's probably best you try this yourself) if there is either no delay (which is what I want) or a very short delay, the element will either intermittently or continually stay in place, which isn't the desired effect. The higher the delay, the more likely it is to work, although in my actual animation this causes a minor jitter because the animation works in two parts and is not designed to have a delay.
This does seem like the sort of thing that could be a browser bug but I've tested this on Chrome, Firefox 52 and the current version of Firefox, all with similar results. I'm not sure where to go from here as I have been unable to find this issue reported anywhere or any solutions/workarounds. It would be much appreciated if someone could find a way to get this reliably working as intended. :)
Here is the JSFiddle page with an example of what I mean.
The markup and code is also pasted here:
var box = document.getElementById("box");
//Reduce this value or set it to 0 (I
//want rid of the timeout altogether)
//and it will only function correctly
//intermittently.
var delay = 25;
setInterval(function() {
box.style.transition = "none";
box.style.left = "1em";
setTimeout(function() {
box.style.transition = "1s linear";
box.style.left = "11em";
}, delay);
}, 1000);
#box {
width: 5em;
height: 5em;
background-color: cyan;
position: absolute;
top: 1em;
left: 1em;
}
<div id="box"></div>
Force the DOM to recalculate itself before setting a new transition after reset. This can be achieved for example by reading the offset of the box, something like this:
var box = document.getElementById("box");
setInterval(function(){
box.style.transition = "none";
box.style.left = "1em";
let x = box.offsetLeft; // Reading a positioning value forces DOM to recalculate all the positions after changes
box.style.transition = "1s linear";
box.style.left = "11em";
}, 1000);
body {
background-color: rgba(0,0,0,0);
}
#box {
width: 5em;
height: 5em;
background-color: cyan;
position: absolute;
top: 1em;
left: 1em;
}
<div id="box"></div>
See also a working demo at jsFiddle.
Normally the DOM is not updated when you set its properties until the script will be finished. Then the DOM is recalculated and rendered. However, if you read a DOM property after changing it, it forces a recalculation immediately.
What happens without the timeout (and property reading) is, that the style.left value is first changed to 1em, and then immediately to 11em. Transition takes place after the script will be fihished, and sees the last set value (11em). But if you read a position value between the changes, transition has a fresh value to go with.
Instead of making the transition behave as an animation, use animation, it will do a much better job, most importantly performance-wise and one don't need a timer to watch it.
With the animation events one can synchronize the animation any way suited, including fire of a timer to restart or alter it.
Either with some parts being setup with CSS
var box = document.getElementById("box");
box.style.left = "11em"; // start
box.addEventListener("animationend", animation_ended, false);
function animation_ended (e) {
if (e.type == 'animationend') {
this.style.left = "1em";
}
}
#box {
width: 5em;
height: 5em;
background-color: cyan;
position: absolute;
top: 1em;
left: 1em;
animation: move_me 1s linear 4;
}
#keyframes move_me {
0% { left: 1em; }
}
<div id="box"></div>
Or completely script based
var prop = 'left', value1 = '1em', value2 = '11em';
var s = document.createElement('style');
s.type = 'text/css';
s.innerHTML = '#keyframes move_me {0% { ' + prop + ':' + value1 +' }}';
document.getElementsByTagName('head')[0].appendChild(s);
var box = document.getElementById("box");
box.style.animation = 'move_me 1s linear 4';
box.style.left = value2; // start
box.addEventListener("animationend", animation_ended, false);
function animation_ended (e) {
if (e.type == 'animationend') {
this.style.left = value1;
}
}
#box {
width: 5em;
height: 5em;
background-color: cyan;
position: absolute;
top: 1em;
left: 1em;
}
<div id="box"></div>

jQuery doesn't show and hide the header

I'm trying to make a header that appears at a certain place of the page.
So what I'm doing is checking the scroll to top of the page and the top offset of the element after which the header should appear. If the scrollTop is greater than offset the header is shown, otherwise it disappears.
But! When I scroll to the place, the header position is constantly switching between top: -13% and top: -12.999998%. After some time it finally shows the header but it never disappears.
What am I doing wrong?!
JSFiddle: https://jsfiddle.net/5k5s016f/
Well, i think the problem is that the .animate() functions are running constantly, causing the animations to "restart" before its ends.
It is not the most beautiful solution, but just adding a flag that controls the execution of the functions and a timeout to run the handler less frequently solves the problem.
https://jsfiddle.net/5k5s016f/2/
var visible = false;
$(window).scroll(function() {
setTimeout(function(){
var height = $(window).scrollTop();
var $page2 = $("#page2");
var offset = $page2.offset().top;
if (height > offset) {
if (visible) {
return;
}
visible = true;
$(".floating-header").show().animate({
top: 0
});
} else {
if (!visible) {
return;
}
visible = false;
$(".floating-header").animate({
top: "-13%"
});
}
}, 200)
});
The issue you are seeing is because each time a scroll event gets called animation queues up. If you wait long enough, you can see that the animation to set top to 0 actually works.
You can use the stop() function to stop all animation before attempting to run another one.
Something like this
if (height > offset) {
$(".floating-header").stop().show().animate({
top: "0"
}, 700);
} else {
$(".floating-header").stop().animate({
top: "-13%"
}, 700);
}
A couple of improvements I can suggest are
Debounce the scroll event handler
Check the current state of the header before queuing animation. i.e. do not try to hide it if it is already hidden and vice versa
Your logic is all messed up. Basically, you want to make sure that you are only animating when you absolutely need to - no more, no less. And since scroll events happen hundreds of times... constantly rapid firing as the user scrolls... you want to make sure you are doing the least amount of work possible during each scroll event. This especially means that you don't want to be querying the DOM on every scroll event if you don't have to (ps. $('selector') is a dom query). Take a look at this fiddle:
https://jsfiddle.net/5k5s016f/6/
Looks like I'm last to the party due to interruptions, but since I wrote it up I'll post the answer FWIW.
jsFiddle Demo
You need to debounce your code. Here is a simple system, but studing Ben Alman's explanation/examples is also recommended.
var $m1 = $('#m1'), $m2 = $('#m2'); //TESTING ONLY
var $win = $(window), $page2 = $("#page2"), $hdr=$(".floating-header");
var $offset = $page2.offset().top;
var hvis = false, curpos;
$win.scroll(function() {
curpos = $win.scrollTop();
$m1.html(curpos); //TESTING ONLY
$m2.html($offset);//TESTING ONLY
if ( curpos > $offset ) {
if ( !hvis ){
hvis = true;
//$m1.html(curpos);
$hdr.finish().animate({
top: "0"
}, 700);
}
} else {
if ( hvis ){
$hdr.finish().animate({
top: "-60px"
}, 700);
hvis = false;
}
}
});
html,
body {
height: 100vh;
width: 100vw;
}
#page1,
#page2,
#page3 {
height: 100%;
width: 100%;
background-color: #fff;
}
.floating-header {
position: fixed;
top: -60px;
background-color: #000;
width: 100%;
height: 60px;
}
.msg{position:fixed;bottom:10px;height:30px;width:80px;text-align:center;}
.msg{padding-top:10px;}
#m1 {left:3px; border:1px solid orange;background:wheat;}
#m2 {right:3px;border:1px solid green; background:palegreen;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<header class="floating-header">Header</header>
<div id="page1">
<p>Page1</p>
</div>
<div id="page2">
<p>Page2</p>
</div>
<div id="page3">
<p>Page3</p>
</div>
<div id="m1" class="msg"></div>
<div id="m2" class="msg"></div>

Image slider hover stop and animated transition

I was testing out coding an image slider as a project to learn HTML, CSS and Javascript and it works great. I'd just like to implement a few tweaks on it and was wondering if anyone had any idea on how to do this. Bear in mind, I'm relatively new to this so a few explanatory comments would be greatly appreciated.
Here are the tweaks I'd like to implement: When the user hovers over the image, I'd like the slider to stop on that particular image so the user can look at it for as long as they wish. The slider resumes once the mouse is moved (a topic not explored on any questions here as far as I can find). Another thing I'd like to be able to do is create a more aesthetic fade transition between the images. There are tutorials out there for this but they don't give a lot of context for a beginner like me to implement it. Here's the jsfiddle, as requested, http://jsfiddle.net/7m9j0ttL/
<html>
<head>
<style type="text/css">
.container {
max-width: 400px;
background-color: black;
margin: 0 auto;
text-align: center;
position: relative;
}
.container div {
background-color: white;
width: 100%;
display: inline-block;
display: none;
}
.container img {
width: 100%;
height: auto;
}
</style>
</head>
<body>
<section class="demo">
<div class="container">
<div style="display: inline-block;">
<img src="Chrysanthemum.jpg" width="1024" height="768" />
</div>
<div>
<img src="Desert.jpg" width="1024" height="768" />
</div>
<div>
<img src="Hydrangeas.jpg" width="1024" height="768" />
</div>
</div>
</section>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
var currentIndex = 0,
items = $('.container div'),
itemAmt = items.length;
function cycleItems() {
var item = $('.container div').eq(currentIndex);
items.hide();
item.css('display', 'inline-block');
}
var autoSlide = setInterval(function() {
currentIndex += 1;
if (currentIndex > itemAmt - 1) {
currentIndex = 0;
}
cycleItems();
}, 9000);
});
</script>
</body>
</html>
Updated your fiddle
$('.demo').hover(function(){
clearInterval(autoSlide);
},function(){
autoSlide = setInterval(function() {
currentIndex += 1;
if (currentIndex > itemAmt - 1) {
currentIndex = 0;
}
cycleItems();
}, 1000);
});
Added a hover handler to the .demo element. Cleared interval on hover, this would help stop the slide show. And re-set interval on mouseout to start the slideshow per the set interval.
I don't know whether such kind of answer is acceptable for you, but someday, a few years ago, I created my own slider when I was studying jquery.
Looking at your code, I have questions:
1. Why don't you use rather standard functions like fadeIn() and fadeOut() for transitions?
2. Why don't you make a function that will be able to run simultaneously with any number of tags on the page?
A few years ago I had these questions in my head and I came here, to stackoverflow to learn how to do that from other people. And I learnt (not only here, though).
And I created a function that could be loaded anywhere in the code - I studied how to do that. Then I added fade and slide effects there and also any other things...
This function is not really good, but PROBABLY it will sched some light for you in slider creation process. Sorry for many words, check what I have here:
https://jsfiddle.net/7m9j0ttL/3/
I hope my effort is useful for you. If you are going to go further with this and have questions - I would be glad to answer them.
Last comments:
So my main aim was to create function that could be ran like this:
$('.container').okwbSlider({ActAsDefined: 'fadeItOut', SlidingTag: 'div', timeOut: 3000});
so, here you can see that almost ANY tag, containing ANY other tags (with images, text etc in it) can be slided.
in order to make everything slided after some time, I thought that I have to break function in 2 parts: one accepts parameters and the second is called using javascript's setInterval.
So, here's the first one:
(function($){
$.fn.okwbSlider = function(params) {
//outer variables
var tgDfnr = this;
var somevar = this;
var MouseStatevar = 0;
var globalTimervar = (params.globalTimervar != undefined) ? params.globalTimervar : 4000;
var ActAsDefined = (params.ActAsDefined != undefined) ? params.ActAsDefined : "fadeItOut";
var SlidingTag = (params.SlidingTag != undefined) ? params.SlidingTag : 'img';
var numberOfChildren = tgDfnr.children(SlidingTag).length;
// alert('tgDfnr='+tgDfnr+' globalTimervar='+globalTimervar+' ActAsDefined='+ActAsDefined+' numberOfChildren='+numberOfChildren);
//alert("<"+tgDfnr.prop("tagName")+" id="+tgDfnr.attr('id')+">");
if (numberOfChildren > 1){
setInterval(function(){
okwbSlideIt(tgDfnr, ActAsDefined, numberOfChildren, MouseStatevar, SlidingTag);
}, globalTimervar);
}
if(numberOfChildren == 1){
tgDfnr.children(SlidingTag).fadeIn(500, function(){
$(this).addClass('active');
});
}
}
})(jQuery);
it contains everything that needed to run the function in jquery-like way (i.e. placing it after $('.yourANYClassNameOrId'))
and the second one (it's place higher in the text - re-accepts the entered parameters and works with them. It's written not in the really best way (I would write it much better now), but at least I think if you look at it, you can understand something useful.
So, let me know if you have questions and/or I can help you further.

Categories

Resources