I'm trying to make my div element move back and forth inside a container infinitely.
The goal is to use Java Script only, no CSS animations, jQuery, etc.
const container = document.getElementById('container');
const box = document.getElementById('box');
let t = setInterval(move, 1);
let pos = 1;
function move() {
box.style.left = pos + 'px';
box.style.top = pos + 'px';
pos++;
if (pos === 150) {
clearInterval(t)
}
}
#container{
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
#box{
width: 50px;
height: 50px;
background-color: red;
position: absolute;
animation-direction: alternate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animation</title>
<link href="animation.css" rel="stylesheet">
<script defer src="animation.js"></script>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
</body>
</html>
So here the code. As you see, I've used position relative/absolute to make the element move with setInterval function. But when I try to reverse it back to "it's corner", it just won't work. To be honest, I've tried some stuff already, but I really can't find the solution of doing it without using any other instruments.
Thanks in advance.
You need to increase/decrease the values considering a boolean variable like below:
const container = document.getElementById('container');
const box = document.getElementById('box');
let t = setInterval(move, 1);
let pos = 1;
let test = true;
function move() {
box.style.left = pos + 'px';
box.style.top = pos + 'px';
if (test)
pos++; /* move down */
else
pos--; /* move up */
/* update the direction when you reach the top or bottom limit*/
if (pos >= 150)
test = false
else if (pos <= 0)
test = true;
}
#container {
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
#box {
width: 50px;
height: 50px;
background-color: red;
position: absolute;
}
<div id="container">
<div id="box"></div>
</div>
An alternative to get the same results
const box = document.getElementById('box');
let jump = 1;
let pos = 0;
window.setInterval(() => {
pos = pos + jump;
if (pos > 150 || pos < 0) {
jump = jump * (-1);
}
box.style.left = pos + 'px';
box.style.top = pos + 'px';
}, 1);
#container{
width: 200px;
height: 200px;
background-color: green;
position: relative;
}
#box{
width: 50px;
height: 50px;
background-color: red;
position: absolute;
animation-direction: alternate;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Animation</title>
<link href="animation.css" rel="stylesheet">
<script defer src="animation.js"></script>
</head>
<body>
<div id="container">
<div id="box"></div>
</div>
</body>
</html>
Related
I'm trying to make a sample where when the user click on the window, the circle (div) will move to that place with a transition. However, it does not work on the first click, but all the others. So I wonder what's making it do that.
<!doctype html>
<html>
<head>
<title>Hover</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="CSS/mystyles.css" >
</head>
<body>
<div id = "divGroup" class = 'group'>
</div>
<script src="JS/code.js"></script>
</body>
</html>
the javascript (i'm using javascript to receive the values and define new values:
var divGroup = document.getElementById("divGroup");
window.onclick = function(evt) {
divGroup.style.left = (evt.clientX - 25) + "px";
divGroup.style.top = (evt.clientY - 25) + "px";
}
the css:
#divGroup {
width: 50px;
height:50px;
background-color:lightblue;
border-radius:50%;
position: absolute;
transition: all 0.5s;
}
You should add initial left and top values in css for #divGroup
var divGroup = document.getElementById("divGroup");
window.onclick = function(evt) {
divGroup.style.left = (evt.clientX - 25) + "px";
divGroup.style.top = (evt.clientY - 25) + "px";
}
#divGroup {
width: 50px;
height: 50px;
background-color: lightblue;
border-radius: 50%;
position: absolute;
transition: all 0.5s;
left: 0;
top: 0;
}
<div id="divGroup" class='group'>
I have created a button which should shift the window's Y to "BOX - 5" div's Y middle through onclick. So in other words I want to set the "Box - 5" div in the middle of the window. I have tried many methods using window.scrollTo and using elements.innerHeight/2, but I still cannot center the element to the middle of the window/screen. Please Help.
I wish to only use Javascript, but if its not possible with it then I would accept jQuery script.
index.html:
window.onbeforeunload = function () {
this.scrollTo(0, 0);
}
var content = document.getElementById("content"),
current = 0;
for (var y=0;y<10;y++) {
var box = document.createElement("div");
box.id = "box";
box.innerHTML = "Box - " + (y+1);
content.appendChild(box);
}
document.querySelector("BUTTON").onclick = function() {
var box_5 = document.querySelectorAll("#box")[4];
/*
NEED HELP HERE
*/
}
body {
margin: 0;
}
#box {
position: relative;
height: 500px;
width: 100%;
margin: 5% auto 5% auto;
color: black;
background-color: skyblue;
border: black 1px solid;
font-size: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>CLICK TO SET THE WINDOW'S Y MIDDLE TO (BOX 5)'s Y MIDDLE</button>
<div id="content"></div>
</body>
</html>
Updated your snippet as below. You can use DOM element property offsetTop to check its Y position and use window.scroll to scroll the view to that element. Another sidenote, it's better to not assign the same id to multiple elements, so I change the id property to class and added identifier _{index} for the class name.
window.onbeforeunload = function () {
this.scrollTo(0, 0);
}
var content = document.getElementById("content"),
current = 0;
for (var y=0;y<10;y++) {
var box = document.createElement("div");
box.className += "box _" + (y+1);
box.innerHTML = "Box - " + (y+1);
content.appendChild(box);
}
document.querySelector("BUTTON").onclick = function() {
var box_5 = document.querySelectorAll(".box._5")[0];
if (box_5) {
// scroll the window view to the element
window.scroll({
top: box_5.offsetTop,
behavior: 'smooth',
})
}
}
body {
margin: 0;
}
.box {
height: 500px;
width: 100%;
margin: 5% auto 5% auto;
color: black;
background-color: skyblue;
border: black 1px solid;
font-size: 50px;
text-align: center;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<button>CLICK TO SET THE WINDOW'S Y MIDDLE TO (BOX 5)'s Y MIDDLE</button>
<div id="content"></div>
</body>
</html>
Sorry for the ambiguous title, not sure how to phrase it.
I have an html page that has 2 iframes side by side with 100% height. I'm trying to set the maximum width of the iframe on right.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<div id="content-wrapper">
<div id="content">
<div id="holder_Iframe1">
<iframe id="iframe1" src="https://en.wikipedia.org/wiki/Mercedes-Benz"></iframe>
<div id="drag"></div>
</div>
<div id="holder_Iframe2">
<iframe id="iframe2" src="http://www.dictionary.com/browse/mercedes?s=t"></iframe>
</div>
</div>
</div>
</body>
</html>
Both iframes are wrapped by divs. Hover the mouse between the iframes to be see the re-size cursor.
I'm setting a maximum width of the iframe2 (the one on the right) of 560px, but when resizing, sometimes it passes that maximum width so I can't resize it back. I'm trying to fix that.
function Resize(e) {
var rightPanePx = document.documentElement.clientWidth - parseInt(holder_Iframe1.style.width, 10);
console.log(rightPanePx);
if ((rightPanePx >= 25) && (rightPanePx <= 560)) {
holder_Iframe1.style.width = (e.clientX - holder_Iframe1.offsetLeft) + "px";
iframe1.style.width = Math.max((holder_Iframe1.style.width.replace("px", "") - 4), 0) + "px";
holder_Iframe2.style.width = (document.documentElement.clientWidth - holder_Iframe1.style.width.replace("px", "")) + "px";
iframe2.style.width = holder_Iframe2.style.width;
}
}
I have attached the code that demonstrates my problem.
var iframe1 = document.getElementById("iframe1");
var iframe2 = document.getElementById("iframe2");
var holder_Iframe1 = document.getElementById("holder_Iframe1");
var holder_Iframe2 = document.getElementById("holder_Iframe2");
var dragEl = document.getElementById("drag");
holder_Iframe1.style.width = (Math.max(document.documentElement.clientWidth, window.innerWidth || 0) * 0.8) + "px";
iframe1.style.cssText = 'width:' + ((Math.max(document.documentElement.clientWidth, window.innerWidth || 0) * 0.8) - 5) + 'px;height:100%;';
dragEl.addEventListener('mousedown', function(e) {
//create overlay so we will always get event notification even though the pointer is hovering iframes
var overlay = document.createElement('div');
overlay.id = "overlay";
document.body.insertBefore(overlay, document.body.firstChild);
window.addEventListener('mousemove', Resize, false);
window.addEventListener('mouseup', stopResize, false);
}, false);
function Resize(e) {
var rightPanePx = document.documentElement.clientWidth - parseInt(holder_Iframe1.style.width, 10);
console.log(rightPanePx);
if ((rightPanePx >= 25) && (rightPanePx <= 560)) {
holder_Iframe1.style.width = (e.clientX - holder_Iframe1.offsetLeft) + "px";
iframe1.style.width = Math.max((holder_Iframe1.style.width.replace("px", "") - 4), 0) + "px";
holder_Iframe2.style.width = (document.documentElement.clientWidth - holder_Iframe1.style.width.replace("px", "")) + "px";
iframe2.style.width = holder_Iframe2.style.width;
}
}
function stopResize(e) {
//remove event listeners from improved performance
window.removeEventListener('mousemove', Resize, false);
window.removeEventListener('mouseup', stopResize, false);
//remove fake overlay
document.getElementById("overlay").remove();
}
html {
overflow-y: hidden;
}
body {
width: 100%;
}
iframe,
#holder_Iframe1,
#holder_Iframe2 {
margin: 0;
padding: 0;
border: 0;
}
iframe {
width: 100%;
height: 100%;
min-width: 0;
}
#content-wrapper {
display: table;
width: 100%;
height: 100%;
top: 0px;
left: 0px;
position: absolute;
}
#content {
display: table-row;
}
#holder_Iframe1,
#holder_Iframe2 {
display: table-cell;
min-width: 0 !important;
}
#holder_Iframe1 {
width: 80%;
}
#drag {
height: 100%;
width: 3px;
cursor: col-resize;
background-color: rgb(255, 0, 0);
float: right;
}
#drag:hover {
background-color: rgb(0, 255, 0);
}
#drag:active {
background-color: rgb(0, 0, 255);
}
#overlay {
background-color: rgba(0, 0, 0, 0);
width: 100%;
height: 100%;
z-index: 10;
top: 0;
left: 0;
position: fixed;
cursor: col-resize;
}
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title></title>
</head>
<body>
<div id="content-wrapper">
<div id="content">
<div id="holder_Iframe1">
<iframe id="iframe1" src="https://en.wikipedia.org/wiki/Mercedes-Benz"></iframe>
<div id="drag"></div>
</div>
<div id="holder_Iframe2">
<iframe id="iframe2" src="http://www.dictionary.com/browse/mercedes?s=t"></iframe>
</div>
</div>
</div>
</body>
</html>
You need to use cursor's position to detect where the direction is.
By adding e.pageX to your function to determine whether resize it or not.
In your sample this may be if (window_size - e.pageX < 560) go resize it, otherwise don't resize.
This question already has answers here:
JS function named `animate` doesn't work in Chrome, but works in IE
(3 answers)
Closed 6 years ago.
I am trying to make an animation in JavaScript, but there is an error i cannot find because my code won't work. I am trying to get the blue box to move diagonally from left to right but it just stays still. Please help.
function animate() {
var elem = document.getElementById('ani');
var pos = 0;
var id = setInterval(frame, 3);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
#box {
background: red;
width: 400px;
height: 400px;
position: relative;
}
#ani {
background: blue;
width: 50px;
height: 50px;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<link rel='stylesheet' href='style.css' />
<script src='script.js'></script>
<title>Practice</title>
</head>
<body>
<p>
<button onclick="animate()">OK</button>
</p>
<div id="box">
<div id="ani"></div>
</div>
</body>
</html>
Use different function name than animate. [Ref]
The Element.animate() method is a shortcut method for creating and playing an animation on an element. And when global function animate() is declared, it is shadowed by Element.prototype.animate
Try this:
function animateMe() {
var elem = document.getElementById('ani');
var pos = 0;
var id = setInterval(frame, 3);
function frame() {
if (pos == 350) {
clearInterval(id);
} else {
pos++;
elem.style.top = pos + "px";
elem.style.left = pos + "px";
}
}
}
#box {
background: red;
width: 400px;
height: 400px;
position: relative;
}
#ani {
background: blue;
width: 50px;
height: 50px;
position: absolute;
}
<p>
<button onclick="animateMe()">OK</button>
</p>
<div id="box">
<div id="ani"></div>
</div>
Note: As explained in the provided reference, you can use window.animate() as it will not refer to shadowed prototype but Global animate function
Fiddle here
I've made margin of 2 divs move (using variable and variable++ or -- with style attribute in js to change margin) Like that:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset="utf-8" />
<title>Game</title>
<style>
body{
position: absolute;
background: #f00;
}
.point{
position: absolute;
width: 15px;
height: 15px;
background: #fff;
border-radius: 10px;
margin: 0px 0 0;
}
.player{
position: absolute;
text-align: center;
width: 200px;
height: 20px;
background: #0005ff;
margin: 550px 550px 0px;
}
</style>
<script>
var num = 550;
$(document).keydown(function (event) {
switch (event.keyCode) {
// Left Arrow
case 37: num = num-- - 15;
document.getElementById('player').style.margin = '550px ' + num + 'px 0px';
break;
// Right Arrow
case 39: num = 15 + num++;
document.getElementById('player').style.margin = '550px ' + num + 'px 0px';
break;
}
});
var nump = 0;
$(document).load(function () {
nump++;
document.getElementById('point').style.margin = nump + 'px 0px 0px';
});
</script>
</head>
<body>
<div class="point" id="point"></div>
<div class="player" id="player"></div>
</body>
</html>
Now I got problem about moving div named point.The div, point is not moving when I use $(document).load but the other div works. How can I fix that?
My second question is how can i check when div "point" touch div "player" then i'll return div point to the start and make a loop.
try this to move the point
var nump = 0;
var touch = false;
var flagtouch;
$(document).ready(function () {
flagtouch = setInterval(function(){
movePoint(nump);
},1000);
});
function movePoint()
{
document.getElementById('point').style.margin = nump + 'px 0px 0px';
touch = chekTouch(); // check whether the divs touches and return true if touched
if(touch)
{
clearInterval(flagtouch);
}
else
{
nump = nump+5;
}
}
For the second question:
With http://api.jquery.com/position/, you can known the position of both divs, and as you know too the width and height of the elements, you can calculate the region occupied by each element, and then when the elements touch each other.