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>
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),
);
I need auto scrolling image placed inside a div. I saw a code for horizontal auto scroll on this page
http://www.dynamicsights.com/cssscrollback.php
I modified it a little to turn it into vertical auto scroll, but for some reason it stopped working. Can someone please tell me what I did wrong, and is there easier way to make vertical auto scroll?
<div id="scroller"></div>
css:
#scroller
{
width:250px; height:120px;
background-image:url(images/background.png); /* size of that image is 250x600 */
}
js:
function StartMove()
{
var BGImage = new Image();
BGImage.src = "images/background.png";
window.cssMaxHeight = 600;
window.cssYPos = 0;
setInterval("MoveBackGround()", 50);
}
function MoveBackGround()
{
window.cssYPos ++;
if (window.cssYPos >= window.cssMaxHeight)
{
clearInterval(MoveBackGround())
}
toMove=document.getElementById("scroller");
toMove.style.backgroundPosition="0 "+window.cssYPos+"px";
}
Code has so many global variables and removing the interval is wrong.
(function() {
var cssMaxHeight, cssYPos, interval, moveTo;
function MoveBackGround() {
cssYPos++;
if (cssYPos >= cssMaxHeight) {
window.clearInterval(interval);
}
toMove = document.getElementById("scroller");
toMove.style.backgroundPosition = "0 " + cssYPos + "px";
}
function StartMove() {
var BGImage = new Image();
BGImage.src = "images/background.png";
cssMaxHeight = 600;
cssYPos = 0;
interval = setInterval(MoveBackGround, 50);
}
StartMove();
}());
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 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);
};
I want to use the 'mouse's drag' to drag a background's position around, inside a box.
The CSS:
.filmmakers #map {
width : 920px;
height : 500px;
margin-top : 50px;
margin-left : 38px;
border : 1px solid rgb(0, 0, 0);
cursor : move;
overflow : hidden;
background-image : url('WorldMap.png');
background-repeat : no-repeat;
}
The html:
<div id = "map" src = "WorldMap.png" onmousedown = "MouseMove(this)"> </div>
The Javascript:
function MouseMove (e) {
var x = e.clientX;
var y = e.clientY;
e.style.backgroundPositionX = x + 'px';
e.style.backgroundPositionY = y + 'px';
e.style.cursor = "move";
}
Nothing happens, no errors, no warnings, nothing... I have tried lots of things: an absolutely positioned image inside a div (you can guess why that didn't work), A draggable div inside a div with a background image, a table with drag and drop, and finally I tried this:
function MouseMove () {
e.style.backgroundPositionX = 10 + 'px';
e.style.backgroundPositionY = 10 + 'px';
e.style.cursor = "move";
}
This works, but its not relative to the mouse's position, pageX and pageY don't work either.
A live demo: http://jsfiddle.net/VRvUB/224/
P.S: whatever your idea is, please don't write it in JQuery
From your question I understood you needed help implementing the actual "dragging" behavior. I guess not. Anyway, here's the results of my efforts: http://jsfiddle.net/joplomacedo/VRvUB/236/
The drag only happens when the mouse button, and.. well, it behaves as I think you might want it to. Just see the fiddle if you haven't =)
Here's the code for those who want to see it here:
var AttachDragTo = (function () {
var _AttachDragTo = function (el) {
this.el = el;
this.mouse_is_down = false;
this.init();
};
_AttachDragTo.prototype = {
onMousemove: function (e) {
if ( !this.mouse_is_down ) return;
var tg = e.target,
x = e.clientX,
y = e.clientY;
tg.style.backgroundPositionX = x - this.origin_x + this.origin_bg_pos_x + 'px';
tg.style.backgroundPositionY = y - this.origin_y + this.origin_bg_pos_y + 'px';
},
onMousedown: function(e) {
this.mouse_is_down = true;
this.origin_x = e.clientX;
this.origin_y = e.clientY;
},
onMouseup: function(e) {
var tg = e.target,
styles = getComputedStyle(tg);
this.mouse_is_down = false;
this.origin_bg_pos_x = parseInt(styles.getPropertyValue('background-position-x'), 10);
this.origin_bg_pos_y = parseInt(styles.getPropertyValue('background-position-y'), 10);
},
init: function () {
var styles = getComputedStyle(this.el);
this.origin_bg_pos_x = parseInt(styles.getPropertyValue('background-position-x'), 10);
this.origin_bg_pos_y = parseInt(styles.getPropertyValue('background-position-y'), 10);
//attach events
this.el.addEventListener('mousedown', this.onMousedown.bind(this), false);
this.el.addEventListener('mouseup', this.onMouseup.bind(this), false);
this.el.addEventListener('mousemove', this.onMousemove.bind(this), false);
}
};
return function ( el ) {
new _AttachDragTo(el);
};
})();
/*** IMPLEMENTATION ***/
//1. Get your element.
var map = document.getElementById('map');
//2. Attach the drag.
AttachDragTo(map);
This isn't working because you are passing the element "map" to your MouseMove function, and using it as both an event object and an element. You can fix this painlessly by using JavaScript to assign your event handler rather than HTML attributes:
<div id="map"></div>
And in your JavaScript:
document.getElementById('map').onmousemove = function (e) {
// the first parameter (e) is automatically assigned an event object
var x = e.clientX;
var y = e.clientY;
// The context of this is the "map" element
this.style.backgroundPositionX = x + 'px';
this.style.backgroundPositionY = y + 'px';
}
http://jsfiddle.net/VRvUB/229/
The downside of this approach is that the backgroundPositionX and backgroundPositionY style properties are not supported in all browsers.
You mention "an absolutely positioned image inside a div" which is probably the more compatible solution for this. To make this setup work, you need to set the position of the outer element to relative, which makes absolute child elements use its bounds as zero.
<div id="map">
<img src="" alt="">
</div>
CSS:
#map {
position:relative;
overflow:hidden;
}
#map img {
position:absolute;
left:0;
top:0;
}
Here it is applied to your code: http://jsfiddle.net/VRvUB/232/
This works 100%
Vanilla Javascript
document.getElementById('image').onmousemove = function (e) {
var x = e.clientX;
var y = e.clientY;
this.style.backgroundPositionX = -x + 'px';
this.style.backgroundPositionY = -y + 'px';
this.style.backgroundImage = 'url(https://i.ibb.co/vhL5kH2/image-14.png)';
}
document.getElementById('image').onmouseleave = function (e) {
this.style.backgroundPositionX = 0 + 'px';
this.style.backgroundPositionY = 0 + 'px';
this.style.backgroundImage = 'url(https://i.ibb.co/Ph9MCB2/template.png)';
}
.container {
max-width: 670px;
height: 377px;
}
#image {
max-width: 670px;
height: 377px;
cursor: crosshair;
overflow: hidden;
background-image: url('https://i.ibb.co/Ph9MCB2/template.png');
background-repeat: no-repeat;
}
<div class="container">
<div id="image">
</div>
</div>