I have a function that moves a box when hovering a button. I would like the function to run over and over again every second as long as the mouse hovers over the button. I have tried loops too but I can't get this to work. I would be very thankful if you would look into this.
Here is my code:
<!DOCTYPE html>
<head>
<style>
#box {
position: relative;
top: 20px;
left: 10px;
width: 50px;
height: 50px;
background:#333366;
}
</style>
<script>
function Start() {
setInterval(Move('box'),1000);
}
var value = 0;
function Move(element) {
value += 50;
var box = document.getElementById(element);
box.style.transition = "left 0.2s ease-in-out 0s";
box.style.left = value+'px';
}
</script>
</head>
<body>
<button onmouseover="Start();">Hover to move</button>
<div id="box"></div>
</body>
</html>
Use this:
setInterval(function(){
Move('box')
},1000);
You have to pass a function to setInterval. You were actually calling Move and passing its return value.
something like this maybe?
http://jsfiddle.net/blackjim/HwKb3/1/
var value = 0,
timer,
btn = document.getElementById('btn');
btn.onmouseover = function(){
timer = setInterval(function(){
// your loop code here
Move('box');
}, 1000);
};
btn.onmouseout = function(){
clearInterval(timer);
}
function Move(element) {
value += 50;
var box = document.getElementById(element);
box.style.transition = "left 0.2s ease-in-out 0s";
box.style.left = value + 'px';
}
Try to see jQuery, it might help you in the beginning.
When this line
setInterval(Move('box'),1000);
is executed, Move('box') is evaluated (and executed one), therefore, your argument to setInterval is the return value for it, that is null
Try this:
var value = 0;
function move(element) {
value += 50;
var box = document.getElementById(element);
box.style.transition = "left 0.2s ease-in-out 0s";
box.style.left = value+'px';
// console.log(box);
}
var button = document.getElementById("buttonID");
button.onmouseover = function() {
this.iid = setInterval(function() {
move("boxID");
}, 1000);
};
button.onmouseout = function() {
this.iid && clearInterval(this.iid);
};
Related
I am trying to move an element in a page after the page loads. I'm trying to get the element to load, and then move after three seconds. Instead, the element just moves immediately on the page load. Here is my code so far:
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
}
#animate {
width: 50px;
height: 50px;
position: absolute;
background-color: red;
}
</style>
<body id="body">
<div id="container">
<div id="animate"></div>
</div>
<script>
var elem = document.getElementById("animate");
function myMove(element) {
var posx = 0;
var posy = 25;
var opacity = 0;
var id = setInterval(frame, 40);
function frame() {
if (posx == 10) {
clearInterval(id);
} else {
posx++;
opacity = opacity + .1
element.style.top = posy + "%";
element.style.left = posx + "%";
element.style.opacity = opacity;
}
}
}
document.getElementById("body").addEventListener("load", setTimeout(myMove(elem), 3000))
</script>
</body>
</html>
Any help would be greatly appreciated.
You need to do
setTimeout(() => myMove(elem), 3000)
otherwise it sets a timeout for whatever myMove(elem) returns, which means myMove(elem) runs immediately
So basically you need this:
// Run at DOM loaded
document.addEventListener("DOMContentLoaded", function() {
console.log('DOM is loaded');
// Move
setTimeout(function(){ myMove(elem); }, 3000)
});
OR
// Run at full page load
window.addEventListener("load", function() {
console.log('Page is loaded');
// Move
setTimeout(function(){ myMove(elem); }, 3000)
});
Currently, the myMove methods execute immediately. To avoid this you can use arrow functions supported in ES6 or move myMove to a function
using arrow function (supported in ES6):
document.getElementById('body').addEventListener(
'load',
setTimeout(() => myMove(elem), 3000),
);
Convert to function
document.getElementById('body').addEventListener(
'load',
setTimeout(function () {
myMove(elem);
}, 3000),
);
<!DOCTYPE html>
<html>
<head>
<style>
#steps img{
-webkit-transition: background-image 1.0s linear 0s;
transition: background-image 1.0s linear 0s;
float: left;
display: none;
height: 50px;
width: 50px;
}
</style>
<script>
var i = 0;
var elem;
function nextStep(){
i++;
var img = document.createElement("img");
img.src = "image"+i+".png"
img.width = "50px";
img.height = "50px";
img.id = "step" + i;
document.getElementById("steps").appendChild(img);
elem = document.getElementById(img.id);
elem.style.display = "inline-block";
elem.style.opacity = "0";
setTimeout(slide(),5000);
}
function slide(){
elem.style.opacity = "1";
if(i > 3){
clearTimeout(slide());
clearTimeout(nextStep());
}
setTimeout(nextStep(),5000);
}
</script>
</head>
<body>
<h1>Steps</h1>
<div id="steps">
<script>
nextStep();
</script>
</div>
<p id="text"></p>
</body>
</html>
I have 4 images and i want to create and display them step by step with a css3 effect, it start by executing nextStep() function that creates img child to div and change display and opacity. After that slide() is called, the opacity is set to 1 and we call nextStep() again. when i > 3 we stop displaying. When i test it, it displays the 4 images instantly without any effect
EDIT:
<!DOCTYPE html>
<html>
<head>
<style>
#steps img{
/*
-webkit-transition: background-image 1.0s linear 0s;
transition: background-image 1.0s linear 0s;
*/
float: left;
display: none;
height: 50px;
width: 50px;
}
</style>
<script>
var i = 0;
var elem;
//var slide;
//var nextStep;
function nextStep(){
i++;
var img = document.createElement("img");
img.src = "image"+i+".png"
img.width = "50px";
img.height = "50px";
img.id = "step" + i;
document.getElementById("steps").appendChild(img);
elem = document.getElementById(img.id);
elem.style.display = "inline-block";
//elem.style.opacity = "0";
setTimeout(slide(),2000);
}
function slide(){
//elem.style.opacity = "1";
if(i < 3){
//clearTimeout(slide());
//clearTimeout(nextStep());
setTimeout(nextStep(),2000);
}
}
</script>
</head>
<body>
<h1>Steps</h1>
<div id="steps">
<script>
document.onload = function (){
nextStep();
};
</script>
</div>
<p id="text"></p>
</body>
</html>
You should always wait for the DOM to be fully loaded before doing any operations on it. Use document.onload to execute your script when the document is loaded :
<script>
document.onload = function (){
nextSteps()
};
</script>
Edit :
There is more issues with your code. The clearTimeout function is not needed here. Also, you're not using it right. Quote from the docs at w3schools :
The clearTimeout() method clears a timer set with the setTimeout()
method.
The ID value returned by setTimeout() is used as the parameter for the
clearTimeout() method.
Note: To be able to use the clearTimeout() method, you must use a
global variable when creating the timeout method:
myVar = setTimeout("javascript function",milliseconds); Then, if the
function has not already been executed, you will be able to stop the
execution by calling the clearTimeout() method.
Your slide function should look like this :
function slide(){
elem.style.opacity = "1";
if(i < 3){
setTimeout(nextStep,5000);
}
}
Edit 2 :
setTimeout needs a reference to a function, e.g the name of the function without the parenthesis :
setTimeout(nextStep,5000);
nextStep is a reference to a function
nextStep() is the result returned by the function after its execution (undefined in this case)
I'm trying to make an image that moves to the right on my website. When you click the image, it should move to the left. For now, this doesn't happen, any ideas? If possible, in pure Javascript and no Jquery ;)
Also, if you click the image for a second time, it should move to the right again. Every consecutive time, the image should move to the other side. I guess this would be best with a for-loop?
<script type"text/javascript">
window.onload = init;
var winWidth = window.innerWidth - movingblockobject.scrollWidth; //get width of window
var movingblock = null //object
movingblock.onclick = moveBlockLeft();
function init() {
movingblock = document.getElementById('movingblockobject'); //get object
movingblock.style.left = '0px'; //initial position
moveBlockRight(); //start animiation
}
function moveBlockRight() {
if (parseInt(movingblock.style.left) < winWidth) { // stop function if element touches max window width
movingblock.style.left = parseInt(movingblock.style.left) + 10 + 'px'; //move right by 10px
setTimeout(moveBlockRight,20); //call moveBlockRight in 20 msec
} else {
return;
}
}
function moveBlockLeft () {
movingblock.style.right = parseInt(movingblock.style.right) + 10 + 'px'
}
</script>
Please first go through the Basics of javascript before trying out something .
window.onload = init;
var winWidth = window.innerWidth;
var movingblock = null;
var intervalid = null;
var isLeft = false;
function init() {
console.log('Init');
movingblock = document.getElementById('movingblockobject');
movingblock.style.left = '0px';
intervalid = setInterval(function() {
moveBlock(true);
}, 2000);
movingblock.onclick = function() {
moveBlock(false);
};
}
function moveBlock(isSetInterval) {
if (!isSetInterval)
isLeft = !isLeft;
if (parseInt(movingblock.style.left) < winWidth) {
if (isLeft)
movingblock.style.left = parseInt(movingblock.style.left) - 10 + 'px';
else
movingblock.style.left = parseInt(movingblock.style.left) + 10 + 'px';
} else {
movingblock.style.left = '0px';
}
}
function moveBlockLeft() {
clearInterval(intervalid);
movingblock.style.right = parseInt(movingblock.style.right) + 10 + 'px';
intervalid = setInterval(moveBlockRight, 20);
}
<div id="movingblockobject" style="width:50px;height:50px;border:solid;position: absolute;">
var movingblock = null
this are mistakes you have delclared it as null and next line you are binding click event.Also for assigning click event you should assign the name of the function.
movingblock.onclick = moveBlockLeft;
above is basic bug there are lot like the above.I feel Self learning is much better for basics
try yourself.
try the above it will work but please try yourself
You should CSS3 transition, works like a charm. Just toggle a class "right"
HTML:
<html>
<head>
<style>
#movingblockobject{
width: 40px;
padding: 10px;
position: fixed;
height:10px;
left:0px;
-webkit-transition: left 2s; /* For Safari 3.1 to 6.0 */
transition: left 2s;
}
#movingblockobject.right{
left:200px;
}
</style>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$( document ).ready(function() {
$('#movingblockobject').on('click', function (e) {
$('#movingblockobject').toggleClass("right");
});
});
</script>
</head>
<body>
<div id="movingblockobject" class="demo">add image here</div>
</body>
</html>
Hey guys I need to stop theBox when it moves out of the screeen (500x500)
I dont know how to anyhelp?
<style>
#box { position: absolute; top: 0; left: 0; background-color: green; }
</style>
<script>
onload = function() {
var theBox = document.getElementById("box");
function animate() {
if ("theBox")
theBox.style.left = (theBox.offsetLeft+5)+"px";
theBox.style.top = (theBox.offsetTop+5)+"px";
}
setInterval(animate,100);
}
</script>
</head>
<body>
<div id="box">The box</div>
</body>
Just add a check to see if the next move will take the box up to or over 500. Also, I've added a call to clearInterval() when the box stops, to stop the timer.
onload = function() {
var timer;
var theBox = document.getElementById("box");
function animate() {
if(theBox.offsetLeft+5 < 500 && theBox.offsetTop+5 < 500){
theBox.style.left = (theBox.offsetLeft+5)+"px";
theBox.style.top = (theBox.offsetTop+5)+"px";
} else {
clearInterval(timer);
}
}
timer = setInterval(animate,100);
}
I have added and if statement to check if the height of the page is higher than the offset top of the box:
onload = function() {
var theBox = document.getElementById("box");
function animate() {
if ("theBox")
if(window.innerHeight > (theBox.offsetTop+25)){
console.log(theBox.offsetTop+5)
theBox.style.left = (theBox.offsetLeft+5)+"px";
theBox.style.top = (theBox.offsetTop+5)+"px";
}
}
setInterval(animate,100);
}
Code Pen
I'm looking for the webkitTransition object reference here
function spawnAnimation(what){
//sets the moving element
var moveingEl = document.getElementById(what);
//gives temp transition property
moveingEl.style.WebkitTransition = "left 2s";
// moveingEl.style.webkitTransition = "top 500ms";
var cLeft = moveingEl.style.left
var cleft = Number(cLeft.slice(0, -2));
var cTop = moveingEl.style.top
var cTop = Number(cTop.slice(0, -2));
moveingEl.style.left = cLeft+200 + "px";
}
This does not work.I would like to give the element a transition property, then make it move to the right. When this code is called it just immediately moves to the right with no animation. bummer :(. I don't want to predefine it in CSS, I would like to dynamically add it and then remove it.
You can use style.setProperty to modify any property using its CSS name as string, including -moz-* and -webkit-* properties.
const style = document.getElementById('my-div').style
const prop = (k, v) => style.setProperty(k, v)
function bounce() {
prop("-webkit-transition", "top .5s ease-in");
prop("top", "50px");
setTimeout(() => {
prop("-webkit-transition", "top .75s cubic-bezier(0.390, 0.575, 0.565, 1.000)");
prop("top", "0px");
}, .5 * 1000)
}
prop("-webkit-transition", "top .5s ease-in");
setInterval(bounce, (.75 + .5) * 1000);
#my-div {
background: red;
border-radius: 50%;
width:50px;
height:50px;
position:absolute;
top: 0px;
}
<div id="my-div"></div>
Allow 1ms for the rendered to get the thread back.
setTimeout(function() {
myElement.style.height = '200px'; /* or whatever css changes you want to do */
}, 1);
You can use:
element.style.webkitTransition = "set your transition up here"
I know it's a workaround, but can you use jQuery?
$(moveingEl).css('-webkit-transform', 'translateX(200px)');
<script>
$(document).ready(function(){
var x = 100;
var y = 0;
setInterval(function(){
x += 1;
y += 1;
var element = document.getElementById('cube');
element.style.webkitTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for safari and chrome
element.style.MozTransform = "translateZ(-100px) rotateY("+x+"deg) rotateX("+y+"deg)"; //for firefox
},50);
//for other browsers use: "msTransform", "OTransform", "transform"
});
</script>