In my pursuit to learn javascript I am making the same slider, but with the animation on javascript (using css it is not an issue for me - it was made on the site google), as the one below:
Original Google slider (animation with css):
http://www.google.com/about/datacenters/inside/
My work so far:
http://jsfiddle.net/TS7Xu/3/
<!-- language-all: lang-html -->
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#promo{
display:block;
height: 354px;
width: 790px;
}
.promo-item {
width: 81px;
height: 354px;
float: left;
}
.promo-item.wide {
width: 613px;
}
.threeP {
background-color: rgb(206, 203, 203);
}
.oneP {
background-color: rgb(241, 220, 182);
}
.twoP {
background-color: rgb(187, 217, 226);
}
</style>
</head>
<body>
<div id="promo">
<div class="promo-item twoP wide" id="twoP">
<div>
</div>
</div>
<div class="promo-item threeP" id="threeP">
<div>
</div>
</div>
<div class="promo-item oneP" id="oneP">
<div>
</div>
</div>
</div>
<script type="text/javascript">
var oneP = document.getElementById('oneP');
var twoP = document.getElementById('twoP');
var threeP = document.getElementById('threeP');
step = 1;
function expandPanel1(){
var h = oneP.clientWidth + step;
oneP.style.width = h+"px";
if (h < 614 || h !=614) {
setTimeout("expandPanel1()", 5);
} else { oneP.style.width = 613+"px"; }
}
function expandPanel2(){
var h = twoP.clientWidth + step;
twoP.style.width = h+"px";
if (h < 614 || h !=614) {
setTimeout("expandPanel2()", 5)
} else { twoP.style.width = 613+"px"; }
}
function expandPanel3(){
var h = threeP.clientWidth + step;
threeP.style.width = h+"px";
if (h < 614 || h !=614) {
setTimeout("expandPanel3()", 5)
} else { threeP.style.width = 613+"px"; }
}
//---------------------------------------------
function expandPanel1Minus(){
var h = oneP.clientWidth - step;
oneP.style.width = h+"px";
if (h > 80 || h !=80) {
setTimeout("expandPanel1Minus()", 5)
} else { oneP.style.width = 81+"px"; }
}
function expandPanel2Minus(){
var h = twoP.clientWidth - step;
twoP.style.width = h+"px";
if (h > 80 || h !=80) {
setTimeout("expandPanel2Minus()", 5)
} else { twoP.style.width = 81+"px"; }
}
function expandPanel3Minus(){
var h = threeP.clientWidth - step;
threeP.style.width = h+"px";
if (h > 80 || h !=80) {
setTimeout("expandPanel3Minus()", 5)
} else { threeP.style.width = 81+"px"; }
}
//---------------------------------------------
oneP.onmouseover = function () {
expandPanel1()
expandPanel3Minus()
expandPanel2Minus()
}
twoP.onmouseover = function () {
expandPanel2()
expandPanel3Minus()
expandPanel1Minus()
}
threeP.onmouseover = function () {
expandPanel3()
expandPanel2Minus()
expandPanel1Minus()
}
</script>
I know this example has errors because if a long drive with the mouse on the slider, it begins to "violently" run :) I deliberately lowered animation speed.
Can someone give me some guidance on how to implement this correctly?
Here's a pure JS implementation - JSFiddle link. In case the fiddle didn't get saved, here's the JS bit only. The rest of the HTML is same as the OP. the function go is called on body load.
var f, s, t;
var which;
function go() {
f = document.getElementById('oneP');
s = document.getElementById('twoP');
t = document.getElementById('threeP');
which = s;
f.onmouseover = function() {
foo(this)
};
s.onmouseover = function() {
foo(this)
};
t.onmouseover = function() {
foo(this)
};
}
function foo(e) {
if (e.clientWidth < 613) {
e.style.width = (e.clientWidth) + 10 + "px";
which.style.width = (which.clientWidth - 10) + "px";
setTimeout(function() {
foo(e);
}, 5);
}
else if (e.clientWidth > 613) {
e.style.width = "613px";
which.style.width = "81px";
which = e;
}
}
There is a bit of work left I think, the animation is not fast enough so it is possible to mouse over on another section while the animation is running. I leave that bit to you :)
If you want to save a lot of time, you should do it with jQuery. Try this http://jsfiddle.net/QXRVb/ sollution. In that example, I didn't preferd to resizing divs. I used Z-indexes and jQuery animate to move them. In that way its easier to make a right position for them.
<style>
#promo{
width:900px;
height:300px;
position:absolute;
top:0px;
left:0px;
overflow:hidden;
}
#oneP{
width:600px;
height:300px;
position:absolute;
top:0px;
left:0px;
background:#999;
z-index:1;
}
#twoP{
width:600px;
height:300px;
position:absolute;
top:0px;
left:150px;
background:#ddd;
z-index:0;
}
#threeP{
width:600px;
height:300px;
position:absolute;
top:0px;
left:750px;
background:#666;
z-index:1;
}
</style>
<html>
<div id="promo">
<div id="oneP">
</div>
<div id="twoP">
</div>
<div id="threeP">
</div>
</div>
</html>
<script>
$('#oneP').mouseover(function() {
$('#oneP').animate({
left: 0
},200);
$('#threeP').animate({
left: 750
},200);
$('#twoP').animate({
left: 450
},200);
});
$('#twoP').mouseover(function() {
$('#oneP').animate({
left: -450
},200);
$('#threeP').animate({
left: 750
},200);
$('#twoP').animate({
left: 150
},200);
});
$('#threeP').mouseover(function() {
$('#threeP').animate({
left: 300
},200);
$('#oneP').animate({
left: -450
},200);
$('#twoP').animate({
left: -150
},200);
});
</script>`
With this method you can easily put image tag inside divs.
Related
I'm trying to add an horizontal loop to my page but when I try to add the javascript cargo tells me that the script has been disabled. Why does that happen? Is there a way to implement that java without having problems? Is it right to add the javascript in the tag script at the end? This is where I've took the code from: https://codepen.io/lemmin/pen/bqNBpK
HTML:
<div id="page">
<div class="pane"><div>Looping Horizontal Scroll</div></div>
<div class="pane"><div>2</div></div>
<div class="pane"><div>3</div></div>
<div class="pane"><div>4</div></div>
<div class="pane"><div>5</div></div>
<div class="pane"><div>Last</div></div>
<div class="pane"><div>Looping Horizontal Scroll</div></div>
</div>
CSS:
body{
overflow-x:hidden;
color:#FFF;
font-family:Helvetica;
font-size:200%;
}
#page {
overflow:hidden;
white-space:nowrap;
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
background-color:#CCC;
display:flex;
flex-wrap:no-wrap;
}
.pane {
flex:0 0 100vw;
height:100vh;
display:flex;
position:relative;
align-items:center;
justify-content:center;
background-color: #45CCFF;
}
.pane:nth-child(4n+2) {
background-color: #49E83E;
}
.pane:nth-child(4n+3) {
background-color: #EDDE05;
}
.pane:nth-child(4n+4) {
background-color: #E84B30;
}
.pane:last-child {
background-color: #45CCFF;
}
JS:
<script>
var page = document.getElementById('page');
var last_pane = page.getElementsByClassName('pane');
last_pane = last_pane[last_pane.length-1];
var dummy_x = null;
window.onscroll = function () {
var y = document.body.getBoundingClientRect().top;
page.scrollLeft = -y;
var diff = window.scrollY - dummy_x;
if (diff > 0) {
window.scrollTo(0, diff);
}
else if (window.scrollY == 0) {
window.scrollTo(0, dummy_x);
}
}
// Adjust the body height if the window resizes.
window.onresize = resize;
// Initial resize.
resize();
// Reset window-based vars
function resize() {
var w = page.scrollWidth-window.innerWidth+window.innerHeight;
document.body.style.height = w + 'px';
dummy_x = last_pane.getBoundingClientRect().left+window.scrollY;
}
</script>
I'm new to Stack Overflow.
I have a simple webpage which tries to move a colored div element back and forth.
However when I run it the div element starts moving correctly but after a few seconds it starts shaking madly, as if its boss refused to give it the salary.
Here is my code:
HTML:
<!DOCTYPE html>
<html>
<head>
<title>Move</title>
<link rel="stylesheet" href="D:\Web\CSS\CSS.css"/>
<script src="D:\Web\JS\JS.js">
</script>
</head>
<body>
<div id="container">
<div id="box">
</div>
</div>
</body>
</html>
JavaScript:
window.onload = function() {
var x = 0;
var box = document.getElementById("box");
setInterval(moveRight, 5);
function moveRight() {
if(x >= 150) {
clearInterval();
setInterval(moveLeft, 5);
} else {
x += 1;
box.style.left = x + "px";
}
}
function moveLeft() {
if(x <= 0) {
clearInterval();
setInterval(moveRight, 5);
} else {
x -= 1;
box.style.left = x + "px";
}
}
}
CSS:
body {
background-color: #246;
}
#container {
width: 200px;
height: 50px;
background: #268;
position: relative;
}
#box {
width: 50px;
height: 50px;
background: #2ac;
position: absolute;
}
Plz help me
Thanks
You're not clearing the interval since you're not passing a variable to it, therefore it's not doing anything. If you set the interval to a variable, you can clear the interval when you switch the direction.
Reference: https://www.w3schools.com/jsref/met_win_clearinterval.asp
Here's an example:
(function() {
var direction;
var x = 0;
var box = document.getElementById("box");
// set the initial direction
direction = setInterval(moveRight, 5);
function moveRight() {
if (x >= 150) {
clearInterval(direction);
direction = setInterval(moveLeft, 5);
} else {
x += 1;
box.style.left = x + "px";
}
}
function moveLeft() {
if (x <= 0) {
clearInterval(direction);
direction = setInterval(moveRight, 5);
} else {
x -= 1;
box.style.left = x + "px";
}
}
})();
body {
background-color: #246;
}
#container {
width: 200px;
height: 50px;
background: #268;
position: relative;
}
#box {
width: 50px;
height: 50px;
background: #2ac;
position: absolute;
}
<!DOCTYPE html>
<html>
<head>
<title>Move</title>
</head>
<body>
<div id="container">
<div id="box">
</div>
</div>
</body>
</html>
I am creating a maze game, and I want to detect when the image following the cursor reaches a certain div, the finishing point. I have the image following the mouse, and I have the container that the image will be in. When the image reaches the div, I want something to trigger, lets say an alert. How can I achieve this?
var startMove;
$(document).mousemove(function(e) {
var DIFF_SNAP = 10;
var DIFF_UNSNAP = 100;
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if (!startMove && Math.abs(difLeft) < DIFF_SNAP && Math.abs(difTop) < DIFF_SNAP) {
startMove = true;
$('html').removeClass('showCursor');
} else if (startMove && !(Math.abs(difLeft) < DIFF_UNSNAP && Math.abs(difTop) < DIFF_UNSNAP)) {
startMove = false;
}
if (startMove) {
$("#image").css({
left: e.pageX,
top: e.pageY
});
} else {
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function() {
startMove = false;
})
html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
height:auto;
}
div{
margin-left: 500px;
width: 200px;
height: 50px;
background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>
<div></div>
Jsfiddle: https://jsfiddle.net/3x7cgLdr/25/
if ($('#TargetDiv').is(':hover')) {
// alert('hello');
$("#image").addClass("red");
}else{
$("#image").removeClass("red");
}
Using this .is() function with :hover selector inside the
if(startMove){
}
Section simply does that without any hassle the is() function Check the current matched set of elements against a selector, element, or jQuery object and return true if at least one of these elements matches the given arguments.
.is() function documentation
var startMove;
$(document).mousemove(function(e) {
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if (difLeft < 10 && difLeft > -10 && difTop < 10 && difTop > -10) {
startMove = true;
$('html').removeClass('showCursor');
}
if (startMove) {
$("#image").css({
left: e.pageX,
top: e.pageY
});
if ($('#TargetDiv').is(':hover')) {
// alert('hello');
$("#image").addClass("red");
} else {
$("#image").removeClass("red");
}
} else {
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function() {
startMove = false;
})
html {
cursor: none;
}
html.showCursor {
cursor: default;
}
#image {
position: absolute;
width: 25px;
height: auto;
}
#TargetDiv {
height: 100px;
width: 100px;
background: green;
margin: 100px auto;
}
.red {
border: 1px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png" />
<div id="TargetDiv">
</div>
I have added a class to set border red to the div when it hovers on the div with mouse and cursor image superimposed that is startMove="true".And removes when it is not hovered .I have commented the alert box;You can turn it on if you want
You already have a flag called startMove that is active whenever the cursor is dragged, use the mouseenter event on the target div as follows:
var startMove;
$(document).mousemove(function(e){
var difLeft = $('#image').offset().left - e.pageX;
var difTop = $('#image').offset().top - e.pageY;
if(difLeft < 10 && difLeft > -10 && difTop < 10 && difTop > -10 ){
startMove = true;
$('html').removeClass('showCursor');
}
if(startMove){
$("#image").css({left:e.pageX, top:e.pageY});
}
else{
$('html').addClass('showCursor');
}
});
$(document).mouseleave(function(){
startMove = false;
})
$("#drop").mouseenter(function(){
if(startMove)
alert("Success");
});
.
<img id="image" src="http://static.micheljansen.org/uploads/mac-osx-arrow-cursor.png"/>
<div id="drop">
</div>
.
html {cursor: none;}
html.showCursor{cursor: default;}
#image{
position:absolute;
width:25px;
z-index: 100;
height:auto;
}
#drop{
width:100px;
height:100px;
background:green;
position: absolute;
left:200px;
top: 300px;
z-index:99
}
see a demo: https://jsfiddle.net/hycd913y/
I have written a simple pong game in Javascript. But I am having two problems with it.
I don't know why the ball doesn't deflect off of the computer's paddle which is the "playerB" according to the code.
How can I create some randomness when the ball deflects from the paddles? Currently the game seems very repetitive.
How can I fix these two problems?
Link to Jsfiddle
HTML
<!DOCTYPE html>
<html>
<head>
<title>Pong game</title>
<script type="text/javascript" src="jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="js/pong.js"></script>
<link rel="stylesheet" href="css/pong.css">
</head>
<body>
<header>
<p>
Computer:<span id="scoreB"></span> Human:<span id="scoreA"></span>
</p>
</header>
<div id="playground">
<div id="ball"></div>
<div id="playerA" class="paddle right"></div>
<div id="playerB" class="paddle left"></div>
</div>
</body>
</html>
CSS
html,body{
margin: 0 atuo;
height:100%;
}
#playground{
position: relative;
width:700px;
height:400px;
border: 1px solid grey;
overflow:hidden;
}
#ball{
position: absolute;
background: #fbb;
width:20px;
height:20px;
left:200px;
top:100px;
border-radius:10px;
}
.paddle{
position: absolute;
border:1px solid grey;
width:10px;
height:80px;
}
.left.paddle{
left:0px;
background-color: green;
}
.right.paddle{
right:0px;
background-color: blue;
}
Javascript
$(document).ready(function(){
var values = {
ball:{
speed:5,
x:50,
y:50,
directionX: 1,
directionY: 1,
radius: 10
},
playground:{
width: parseInt($("#playground").width()),
height: parseInt($("#playground").height())
},
playerA:{
y:0,
top: $("#playerA").offset().top,
height: $("#playerA").height(),
width: $("#playerA").width(),
score:0
},
playerB:{
y:0,
top: $("#playerB").offset().top,
height: $("#playerB").height(),
width: $("#playerB").width(),
score:0
}
};
//collision detection
function hitsTopBottom(){
var y = values.ball.y;
return y>values.playground.height-20 || y < 0;
}
function hitsRight(){
return values.ball.x > values.playground.width-20;
}
function hitsLeft(){
return values.ball.x < 0;
}
//ball hits playerA's paddle. Works properly but open to improvement
function hitsPlayerA(){
var ballX = values.ball.x;
var ballY = values.ball.y;
var playerAY = values.playerA.y;
return ballY<=playerAY+values.playerA.height && ballY>playerAY && ballX>=700-values.playerA.width-values.ball.radius;
}
//ball hits playerB's paddle. Doesn't work at all
function hitsPlayerB(){
var ballX = values.ball.x;
var ballY = values.ball.y;
var playerBY = values.playerB.y;
return ballY<=playerBY+values.playerB.height && ballY>=playerBY && ballX<=values.playerB.width-values.ball.radius;
}
//rendering the position of the ball
function renderball(){
$("#ball").css("left",values.ball.x);
$("#ball").css("top",values.ball.y);
$("#scoreB").text(values.playerB.score);
$("#scoreA").text(values.playerA.score);
}
//moving ball
function moveball(){
if(hitsTopBottom()){
values.ball.directionY *= -1;
}
if(hitsPlayerA()){
values.ball.directionX *= -1;
}
if(hitsPlayerB()){
values.ball.directionX = 1;
}
if(hitsRight()){
values.ball.x = 200;
values.ball.y = 200;
values.playerB.score += 1;
}
if(hitsLeft()){
values.ball.x = 200;
values.ball.y = 200;
values.playerA.score += 1;
}
values.ball.x += values.ball.speed*values.ball.directionX;
values.ball.y += values.ball.speed*values.ball.directionY;
renderball();
var playerB_pos = values.ball.y - values.playerB.height/2;
$("#playerB").css("top",playerB_pos);
}
//player movements
$("#playground").mousemove(function(e){
values.playerA.y = e.pageY-values.playerA.top-parseInt($("#playerA").height()/2);
$("#playerA").css("top",values.playerA.y);
});
setInterval(moveball,1000/30);
});
The ball was not deflecting off the computer paddle because its position was not being stored. By setting values.playerB.y = playerB_pos in the loop it will correctly bounce off now. However since it is the same as the y position of the ball the computer will never lose. To correct for this and add some randomness I used jQuery's animate function to tween the computer paddle between points and fake momentum:
if(!isAnimating) {
isAnimating = true;
$("#playerB").animate({"top": playerB_pos}, {
duration: (values.ball.speed*16),
easing: "linear",
step: function( now, fx ) {
values.playerB.y = parseInt($("#playerB").offset().top - parseInt($("#playerA").height()));
},
complete: function() {
isAnimating = false;
}
});
}
You can see it in action here: http://jsfiddle.net/yb290ow9/5/
You forgot to edit the actual playerB.y value (you just changed the css):
var playerB_pos = values.ball.y - values.playerB.height/2;
values.playerB.y = playerB_pos; // Forgot this!
$("#playerB").css("top",playerB_pos);
Working JSFiddle: http://jsfiddle.net/yb290ow9/6/
About the randomness: you could make the paddle "bouncy": change the speed of the ball, not just the direction
I am trying to build an animation effect where a div will float towards another div and when it reaches to the second div area, the floating div will fade out.Moving direction will be like this https://www.dropbox.com/s/2bpdbtycajuuk6a/1.JPG?dl=0 .For better understanding , i am providing my html and css code here.
html code....
<div id="outer_div">
<div class='a'>A</div>
<div class='b'>B</div>
<div class='c'>C</div>
<div class='d'>D</div>
</div>
and css ....
div.a {
width: 50px;
height:50px;
background-color:red;
position:absolute;
bottom:0;
top:450px;
left: 225px;
}
div.b {
width: 50px;
height:50px;
background-color:green;
position:absolute;
bottom:0;
top:225px;
left: 0px;
}
div.c {
width: 50px;
height:50px;
background-color:yellow;
position:absolute;
bottom:450px;
top:0px;
left: 225px;
}
div.d {
width: 50px;
height:50px;
background-color:pink;
position:absolute;
bottom:225px;
top:225px;
left: 450px;
}
#outer_div {
width: 500px;
height:500px;
background-color:blue;
position:fixed;
}
Here are 4 divs(A, B, C, D). A div will float where others are still. At first A div will float towards D and when touches D , A will fade out. Second, A div will float from the beginning towards C and when touches C , A will fade out. Third, A div will float from the beginning towards B and when touches B , A will fade out. Again the annimation will begin from the beginning and continue as before and this procedure will continue for 52 times.I have tried with this script but failed to do it .
Scripts ....
$(document).ready(function () {
animateDiv();
});
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = -$("#outer_div").height() - 50;
var w = -$("#outer_div").width()/2 - 50;
var nh = h;
var nw = w;
// var nh = Math.floor(Math.random() * h);
// var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({top: newq[0], right: newq[1]}, speed, function () {
animateDiv();
});
}
;
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
I couldn't understand the direction concept of the floating div A and how i am gonna detect that my floating div is at in the region of other div. Please help me with its solution and how can i understand animation direction concept in jquery(some reference can help a lot) ?
Try
$(document).ready(function () {
var a = $(".a")
, elems = $("#outer_div div").not(a)
, pos = function () {
return $.map(elems, function (el, i) {
return $(el).css(["left", "top"])
}).reverse()
}
, curr = 0
, max = 52
, speed = 1000;
(function animateDiv(el, p, curr, max) {
if (!!p.length) {
$(el)
.animate({
left:p[0].left
, top: (parseInt(p[0].top) + $(el).height())
}, speed, function () {
$(this).fadeOut(100, function () {
$(this)
.css({"top": "450px", "left":"225px"})
.fadeIn(0);
p.splice(0, 1);
animateDiv(this, p, curr, max)
})
})
} else if (curr < max) {
++curr;
console.log(curr, max);
animateDiv(el, pos(), curr, max)
}
}(a, pos(), curr, max))
});
div.a {
width: 50px;
height:50px;
background-color:red;
position:absolute;
bottom:0;
top:450px;
left: 225px;
}
div.b {
width: 50px;
height:50px;
background-color:green;
position:absolute;
bottom:0;
top:225px;
left: 0px;
}
div.c {
width: 50px;
height:50px;
background-color:yellow;
position:absolute;
bottom:450px;
top:0px;
left: 225px;
}
div.d {
width: 50px;
height:50px;
background-color:pink;
position:absolute;
bottom:225px;
top:225px;
left: 450px;
}
#outer_div {
width: 500px;
height:500px;
background-color:blue;
position:fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="outer_div">
<div class='a'>A</div>
<div class='b'>B</div>
<div class='c'>C</div>
<div class='d'>D</div>
</div>
jsfiddle http://jsfiddle.net/83h17z25/2/