make a div move across the screen - javascript

I need to make a colored div move horizontally to the right and when it hits the edge it should double in size and twice the speed rotating around the center.
var topPosition = 50;
var leftPosition = 250;
var rightPosition = 800;
function move(){
var go = document.getElementById("box");
go.style.left = leftPosition + "px";
go.style.right = rightPosition + "px";
go.style.visibility = "visible";
++leftPosition;
if (leftPosition == 800){
--leftPosition;
it stops at 800 px like I told it but it wont go back

Let's clean the code up a bit and implement what you want. In order:
Move to 800px
When 1 is done, go back, twice as fast, and double in size.
We'll do this using one scoped variable: speed. speed will be the default speed and direction.
I have also separated your code in setInterval in order to not block execution of the page.
function move() {
var elem = document.getElementById("box"),
speed = 1,
currentPos = 0;
// Reset the element
elem.style.left = 0+"px";
elem.style.right = "auto";
var motionInterval = setInterval(function() {
currentPos += speed;
if (currentPos >= 800 && speed > 0) {
currentPos = 800;
speed = -2 * speed;
elem.style.width = parseInt(elem.style.width)*2+"px";
elem.style.height = parseInt(elem.style.height)*2+"px";
}
if (currentPos <= 0 && speed < 0) {
clearInterval(motionInterval);
}
elem.style.left = currentPos+"px";
},20);
}
Fiddle: http://tinker.io/7d393 . You'll see, it works.

Think about what happens as soon as leftPosition has reached 799:
++leftPosition; #leftPostion == 800
if (leftPosition == 800){ #This becomes true
--leftPosition; #leftPostion == 799
So you start where you left off, and this will repeat on the next time you call move()
To fix this, you need to add a direction to the movement:
var topPosition = 50;
var leftPosition = 250;
var rightPosition = 800;
var direction = 1;
function move(){
var go = document.getElementById("box");
go.style.left = leftPosition + "px";
go.style.right = rightPosition + "px";
go.style.visibility = "visible";
leftPosition += direction;
if (leftPosition == 800){
direction = -1;

Here's a (mostly) CSS solution: http://tinker.io/7d393/6
HTML:
<div id="box"></div>
<div style="position: absolute; top: 200px"><button>Move it</button></div>
CSS:
#box {
background: blue;
position: absolute;
width:100px;
height: 100px;
}
#box.move{
-webkit-animation: myanim 5s;
animation: myanim 5s;
}
#-webkit-keyframes myanim
{
0% {top:0;left:0; width: 100px; height: 100px;}
66% {top:0;left:800px; width:100px;height:100px;}
67% {top:0;left:800px; width:200px; height: 200px;}
100% {top:0; left:0; width: 200px; height:200px;}
}
#keyframes myanim
{
0% {top:0;left:0; width: 100px; height: 100px;}
66% {top:0;left:800px; width:100px;height:100px;}
67% {top:0;left:800px; width:200px; height: 200px;}
100% {top:0; left:0; width: 200px; height:200px;}
}
JS:
//jQuery as I do not know what nav you are using.
$(function() {
$("button").click(function(){
$('#box').toggleClass('move')});
});
Here is a mostly jQuery solution: http://tinker.io/7d393/7
HTML:
<div id="box"></div>
<div style="position: absolute; top: 200px"><button>Move it</button></div>
CSS:
#box {
background: blue;
position: absolute;
width:100px;
height: 100px;
}
JS:
//jQuery as I do not know what nav you are using.
$(function() {
$("button").click(function(){
$('#box')
.css({left:0,top:0,width:'100px',height:'100px'})
.animate({left:'800px',top:0,width:'100px',height:'100px'},3000)
.animate({left:'800px',top:0,width:'200px',height:'200px'},20)
.animate({left:0,top:0,width:'200px',height:'200px'},1500);
});
});

Related

Animating newly created objects with different keyframes values

So I'm trying to make simple animation. When you press somewhere inside blue container, a circle should be created in this place and then go up. After some research I found how to put JS values into keyframes, but it's changing values for every object not just for freshly created. If you run snipped and press somewhere high and then somewhere low you will see what I'm talking about.
I found some AWESOME solution with Raphael library, but I'm a beginner and I'm trying to make something like this in JS. Is it even possible? How?
var bubble = {
posX: 0,
posY: 0,
size: 0
};
var aquarium = document.getElementById("container");
var ss = document.styleSheets;
var keyframesRule = [];
function findAnimation(animName) { //function to find keyframes and insert replace values in them
for (var i = 0; i < ss.length; i++) {
for (var j = 0; j < ss[i].cssRules.length; j++) {
if (window.CSSRule.KEYFRAMES_RULE == ss[i].cssRules[j].type && ss[i].cssRules[j].name == animName) {
keyframesRule.push(ss[i].cssRules[j]);
}
}
}
return keyframesRule;
}
function changeAnimation (nameAnim) { //changing top value to cursor position when clicked
var keyframesArr = findAnimation(nameAnim);
for (var i = 0; i < keyframesArr.length; i++) {
keyframesArr[i].deleteRule("0%");
keyframesArr[i].appendRule("0% {top: " + bubble.posY + "px}");
}
}
function createBubble(e) {
"use strict";
bubble.posX = e.clientX;
bubble.posY = e.clientY;
bubble.size = Math.round(Math.random() * 100);
var bubbleCircle = document.createElement("div");
aquarium.appendChild(bubbleCircle);
bubbleCircle.className = "bubble";
var bubbleStyle = bubbleCircle.style;
bubbleStyle.width = bubble.size + "px";
bubbleStyle.height = bubble.size + "px";
bubbleStyle.borderRadius = (bubble.size / 2) + "px";
//bubbleStyle.top = bubble.posY - (bubble.size / 2) + "px";
bubbleStyle.left = bubble.posX - (bubble.size / 2) + "px";
changeAnimation("moveUp");
bubbleCircle.className += " animate";
}
aquarium.addEventListener("click", createBubble);
//console.log(bubble);
body {
background-color: red;
margin: 0;
padding: 0;
}
#container {
width: 100%;
height: 100%;
position: fixed;
top: 80px;
left: 0;
background-color: rgb(20,255,200);
}
#surface {
width: 100%;
height: 40px;
position: fixed;
top: 40px;
opacity: 0.5;
background-color: rgb(250,250,250);
}
.bubble {
position: fixed;
border: 1px solid blue;
}
.animate {
animation: moveUp 5s linear;//cubic-bezier(1, 0, 1, 1);
-webkit-animation: moveUp 5s linear;//cubic-bezier(1, 0, 1, 1);
}
#keyframes moveUp{
0% {
top: 400px;
}
100% {
top: 80px;
}
}
#-webkit-keyframes moveUp{
0% {
top: 400px;
}
100% {
top: 80px;
}
}
<body>
<div id="container">
</div>
<div id="surface">
</div>
</body>
Here is a possible solution. What I did:
Remove your functions changeAnimation () and findAnimation() - we don't need them
Update the keyframe to look like - only take care for the 100%
#keyframes moveUp { 100% {top: 80px;} }
Assign top of the new bubble with the clientY value
After 5 seconds set top of the bubble to the offset of the #container(80px) - exactly when animation is over to keep the position of the bubble, otherwise it will return to initial position
var bubble = {
posX: 0,
posY: 0,
size: 0
};
var aquarium = document.getElementById("container");
function createBubble(e) {
"use strict";
bubble.posX = e.clientX;
bubble.posY = e.clientY;
bubble.size = Math.round(Math.random() * 100);
var bubbleCircle = document.createElement("div");
aquarium.appendChild(bubbleCircle);
bubbleCircle.className = "bubble";
var bubbleStyle = bubbleCircle.style;
bubbleStyle.width = bubble.size + "px";
bubbleStyle.height = bubble.size + "px";
bubbleStyle.borderRadius = (bubble.size / 2) + "px";
bubbleStyle.top = bubble.posY - (bubble.size / 2) + "px";
bubbleStyle.left = bubble.posX - (bubble.size / 2) + "px";
bubbleCircle.className += " animate";
// The following code will take care to reset top to the top
// offset of #container which is 80px, otherwise circle will return to
// the position of which it was created
(function(style) {
setTimeout(function() {
style.top = '80px';
}, 5000);
})(bubbleStyle);
}
aquarium.addEventListener("click", createBubble);
body {
background-color: red;
margin: 0;
padding: 0;
}
#container {
width: 100%;
height: 100%;
position: fixed;
top: 80px;
left: 0;
background-color: rgb(20, 255, 200);
}
#surface {
width: 100%;
height: 40px;
position: fixed;
top: 40px;
opacity: 0.5;
background-color: rgb(250, 250, 250);
}
.bubble {
position: fixed;
border: 1px solid blue;
}
.animate {
animation: moveUp 5s linear;
/*cubic-bezier(1, 0, 1, 1);*/
-webkit-animation: moveUp 5s linear;
/*cubic-bezier(1, 0, 1, 1);*/
}
#keyframes moveUp {
100% {
top: 80px;
}
}
#-webkit-keyframes moveUp {
100% {
top: 80px;
}
}
<body>
<div id="container"></div>
<div id="surface"></div>
</body>
The problem about your code was that it is globally changing the #keyframes moveUp which is causing all the bubbles to move.
The problem with your code is that you're updating keyframes which are applied to all bubbles. I tried another way of doing it by using transition and changing the top position after the element was added to the DOM (otherwise it wouldn't be animated).
The main problem here is to wait the element to be added to the DOM. I tried using MutationObserver but it seems to be called before the element is actually added to the DOM (or at least rendered). So the only way I found is using a timeout which will simulate this waiting, although there must be a better one (because it may be called too early, causing the bubble to directly stick to the top), which I would be happy to hear about.
var bubble = {
posX: 0,
posY: 0,
size: 0
};
var aquarium = document.getElementById("container");
function createBubble(e) {
"use strict";
bubble.posX = e.clientX;
bubble.posY = e.clientY;
bubble.size = Math.round(Math.random() * 100);
var bubbleCircle = document.createElement("div");
aquarium.appendChild(bubbleCircle);
bubbleCircle.classList.add("bubble");
var bubbleStyle = bubbleCircle.style;
bubbleStyle.width = bubble.size + "px";
bubbleStyle.height = bubble.size + "px";
bubbleStyle.borderRadius = (bubble.size / 2) + "px";
bubbleStyle.top = bubble.posY - (bubble.size / 2) + "px";
bubbleStyle.left = bubble.posX - (bubble.size / 2) + "px";
setTimeout(function() {
bubbleCircle.classList.add("moveUp");
}, 50);
}
aquarium.addEventListener("click", createBubble);
body {
background-color: red;
margin: 0;
padding: 0;
}
#container {
width: 100%;
height: 100%;
position: fixed;
top: 80px;
left: 0;
background-color: rgb(20, 255, 200);
}
#surface {
width: 100%;
height: 40px;
position: fixed;
top: 40px;
opacity: 0.5;
background-color: rgb(250, 250, 250);
}
.bubble {
position: fixed;
border: 1px solid blue;
transition: 5s;
}
.moveUp {
top: 80px !important;
}
<body>
<div id="container">
</div>
<div id="surface">
</div>
</body>
Also, I used the classList object instead of className += ... because it is more reliable.

Move div animation onmouseover,onmouseout

My code below:
JavaScript:
function showMenu(){
var t = setInterval(move, 5);
var menu = document.getElementById("menu");
var pos = 0;
function move(){
if(pos>=150){
clearInterval(t);
}
else{
pos += 1;
menu.style.left = pos + "px";
}
}
}
function hideMenu(){
var t = setInterval(move, 10);
var menu = document.getElementById("menu");
var pos = menu.getAttribute("left");
function move(){
if(pos<=0){
clearInterval(t);
}
else{
pos -= 1;
menu.style.left = pos + "px";
}
}
}
HTML:
<div id="menu-field" onmouseover="showMenu()" onmouseout="hideMenu()" >
<div id="menu"></div>
</div>
I want the div element to move right on mouse over and start moving back to starting position on mouse out. This does the showMenu function even on mouse out.
This might be better accomplished natively with CSS and no JavaScript. This looks like it will accomplish what you're trying to do:
#menu-field {
background: #eee;
height: 200px;
width: 80px;
}
#menu {
background: #aaa;
height: 100px;
width: 80px;
transition: transform 1s;
}
#menu-field:hover #menu {
transform: translateX(80px);
}
<div id="menu-field">
<div id="menu">Menu</div>
</div>

Blur background based on page length

I am trying to make so that if you scroll down, a blurred picture appears (with opacity) and if you're at the bottom of the page, the blurred picture is fully visible and the old one disappeared. I'm using the same pagecontainer for every page and I want to make this script do this on every page, with different page lengths.
I have this so far:
CSS:
.img-src {
position: fixed;
background-position: center;
-webkit-background-size: cover;
top: 0;
bottom: 0;
left: 0;
right: 0;
z-index: -1;
}
.blurred-img {
opacity: 0;
}
JS:
var divs = $('.social, .title'),
limit = 0;
$(window).on('scroll', function() {
var st = $(this).scrollTop();
if (st <= limit) {
$('.blurred-img').css({ 'opacity' : (1 - st/limit) });
}
});
filter: blur usually works fine and looks better. How about something like this?
var img = document.getElementById("background-img");
var container = document.body;
var maxBlur = 20;
window.addEventListener("scroll", function(){
var position = container.scrollTop / (container.scrollHeight - window.innerHeight);
// Adjust the position for safari that may scroll higher or lower than the
// actual size during their "bounce effect".
position = Math.max(0, Math.min(1, position));
var blurAmount = position * maxBlur;
img.style["filter"] = "blur(" + blurAmount + "px)";
});
#background-img {
position: fixed;
}
#spacer {
width: 50px;
height: 2000px;
}
<img id="background-img" src="http://placehold.it/400x200?text=Background" />
<div id="spacer"></div>
If you really want to do your two images strategy, here is how I would do it.
var img = document.getElementById("blured-background-img");
var container = document.body;
window.addEventListener("scroll", function(){
var opacity = container.scrollTop / (container.scrollHeight - window.innerHeight);
// Adjust the opacity for safari that may scroll higher or lower than the
// actual size during their "bounce effect".
opacity = Math.max(0, Math.min(1, opacity));
img.style["opacity"] = opacity;
});
#background-img {
position: fixed;
}
#blured-background-img {
position: fixed;
opacity: 0;
}
#spacer {
width: 50px;
height: 2000px;
}
<img id="background-img" src="http://placehold.it/400x200/7A6DFF/D3CFFF?text=Bottom" />
<img id="blured-background-img" src="http://placehold.it/400x200?text=Top" />
<div id="spacer"></div>

animated loads in wrong spot

I have a div that animates up and down which works fine. The issue I'm getting is that every time the page loads the div starts at the very top of the page and then jumps down to where it needs to be after the animation starts.
<body id="body">
<div id="square"></div>
</body>
#body {
background: #000;
}
#square {
background-color: #fff;
margin: 0 auto;
position: relative;
width: 100px;
height: 100px;
}
var box = document.getElementById('square');
TOP = (window.innerHeight - box.offsetHeight)/2;
box.style.top = TOP;
var down = setInterval(animateDown, 15);
var up;
function animateDown()
{
TOP += 3;
box.style.top = TOP + 'px';
if(TOP > 900){
clearInterval(down);
up = setInterval(animateUp, 15);
}
}
function animateUp()
{
TOP -= 3;
box.style.top = TOP + 'px';
if(TOP <= (window.innerHeight - box.offsetHeight)/2){
clearInterval(up);
down = setInterval(animateDown, 15);
}
}
Here is a link to the jsfiddle as well >> https://jsfiddle.net/xgilmore/pLbgvc3L/
thanks in advance
This is sort of a work around, but you can start the box off as hidden, and then once you start animating, set it visible. https://jsfiddle.net/pLbgvc3L/1/
function animateDown()
{
box.style.visibility = 'visible';
#square {
background-color: #fff;
//margin: 0 auto;
position: relative;
width: 100px;
height: 100px;
top: 20%;
visibility: hidden;
}
Oh sorry, I actually know what is going on, it just took a second look to figure it out. top: 20% doesn't do anything because percentages only work if the parent element (body) has an explicit height. Like so https://jsfiddle.net/pLbgvc3L/2/

Image angle changes depending position of mouse

Im trying to build a game where enemies jump out of the water and you fire water at them...
When the user clicks to fire I want the img src to point in the direction of the click, to achieve what I have so far I have css and js script (code below) however it looks to static, I feel having the water point in the direction of the users input would help a lot however Im not sure how to achieve this?
//bind to gun events
this.playfield.on('gun:out_of_ammo',_.bind(function(){this.outOfAmmo();},this));
this.playfield.on('gun:fire',_.bind(function(){
this.flashScreen();
},this));
...
flashScreen : function(){
$(".theFlash").css("display","block");
setTimeout(function(){
$('.theFlash').css("display","none");
},400);
}
CSS
.theFlash{
background-color : transparent;
width:900px;
height:500px;
position:relative;
margin:0 auto;
z-index:10;
display:none;
}
I put together an example below that will hopefully help you out.
You just have to specify the source from where the shoot is fired (sourceX,sourceY), calculate the angle to where the mouse is clicked (done below, so should just be to copy/paste) and adjust the transform: rotate(Xdeg); to the new angle.
Make sure to set the orgin in css with transform-origin, so that the flame rotates around the source and not the flame itself.
Try it out at the bottom.
var game,
flame,
sourceX = 310,
sourceY = 110;
window.onload = function() {
game = document.getElementById('game');
flame = document.getElementById('flame');
game.addEventListener('click', function(e) {
var targetX = e.pageX,
targetY = e.pageY,
deltaX = targetX - sourceX,
deltaY = targetY - sourceY,
rad = Math.atan2(deltaY, deltaX),
deg = rad * (180 / Math.PI),
length = Math.sqrt(deltaX*deltaX+deltaY*deltaY);
fire(deg,length);
}, false);
};
function fire(deg,length) {
flame.style.opacity = 1;
flame.style.transform = 'rotate(' + deg + 'deg)'
flame.style.width = length + 'px';
setTimeout(function() {
flame.style.opacity = 0;
},300);
};
#game {
position: relative;
width: 400px;
height: 200px;
background-color: #666;
overflow: hidden;
}
#source {
border-radius: 50%;
z-index: 101;
width: 20px;
height: 20px;
background-color: #ff0000;
position: absolute;
left: 300px;
top: 100px;
}
#flame {
width: 300px;
height: 3px;
background-color: #00ff00;
position: absolute;
left: 310px;
top: 110px;
opacity: 0;
transform-origin: 0px 0px;
transform: rotate(180deg);
transition: opacity .2s;
}
<div id="game">
<div id="source">
</div>
<div id="flame">
</div>
</div>
I would not recommend building games in this manner, Canvas and SVG are the preferred methods of building browser games, with that said it can be done.
Try this
https://jsfiddle.net/b77x4rq4/
$(document).ready(function(){
var middleOfElementTop = 250; // margin from top + half of height
var middleOfElementLeft = 125; // margin from left + half of width
$("#main").mousemove(function(e){
var mouseX = e.offsetX;
var mouseY = e.offsetY;
var angle = Math.atan2(mouseY - middleOfElementTop, mouseX - middleOfElementLeft) * 180 / Math.PI;
$(".box").css({"transform": "rotate(" + angle + "deg)"})
})
});

Categories

Resources