I am writing some code that makes a div slide to the left or the right of the page depending on some key press (left or right arrows). Here is my script.
$(document).keydown(function(e){
var $inner = $('.inner-cover');
if (e.keyCode == 39) {
$inner.css({
position: 'fixed',
top: $inner.offset().top,
left: $inner.offset().left
}).animate({left:'100%'}, 1000);
}
if (e.keyCode == 37){
$inner.css({
position: 'fixed',
top: $inner.offset().top,
right: $inner.offset().right
}).animate({right:'100%'}, 1000);
}
});
and here is a link to it in jsfiddle.
http://jsfiddle.net/e32A3/
I have a few questions about it that I'd really like answered because I don't seem to understand this properly.
Why does the slide function only work one or two times?
Why do I need to put
$inner.css({}).animate({left:'100%'},1000);
I tried
$inner.animate({left:100%},1000);
and it did not work
Also how would I stop it in the center? I'm figuring that I have to do something along the lines of
animate({left:($(window).width()-$inner.width())/2)},1000);
but again I've tried that and it didn't work.
Try this:
if (e.keyCode == 37){
$inner.css({
position: 'fixed',
top: $inner.offset().top
}).animate({left:'-100%'}, 1000);}
Working Demo
Try this:
$(document).keydown(function (e) {
var $inner = $('.inner-cover');
if (e.keyCode == 39) {
$inner.css({
position: 'fixed',
top: $inner.offset().top,
left: $inner.offset().left
}).animate({
left: '100%',
right: 'auto'
}, 1000);
}
if (e.keyCode == 37) {
$inner.css({
position: 'fixed',
top: $inner.offset().top,
}).animate({
right: '100%',
left: 'auto'
}, 1000);
}
});
Added right to "auto" instead of offset().right , there is nothing as offset().right. Offset contains only top and left values.
Demo: http://jsfiddle.net/lotusgodkk/e32A3/2/
Why does the slide function only work one or two times?
Because in the second run it has already property "left:100%"
Why do I need to put
Because setting "left" or "right" will take effect only if position of element setted to fixed/absolute/relative
Also how would I stop it in the center?
To set in the center set
$inner.animate({left:window.(innerWidth-$inner.width)/2+"px"})
Finally you need to operate with one of attr "left" or "right" and set the position of element in CSS
JS:
$(document).keydown(function(e){
var $inner = $('.inner-cover');
if (e.keyCode == 39) {
$inner.animate({left:($(window).width() - $inner.width())+"px"}, 1000);
//this to set on middle//$inner.animate({left:($(window).width() - $inner.width())/2+"px"}, 1000);
}
if (e.keyCode == 37){
$inner.animate({left:0}, 1000);
}
});
CSS:
.inner-cover {
position:fixed;
width:200px;
left:50%;
top:50%;
background-color:green;
}
Related
I am new to using javascript and jquery so I'm having some problems figuring this one out.
I am trying to use the animate function in jquery to move a box from one corner to the next.
The box begins on the top-left corner of the screen and upon clicking the 'go' button, it will move to the next corner (top-right).
Clicking the same 'go' button then moves the box to the next corner (bottom-right).
Clicking the 'go' button once more will move it to the next corner (bottom-left).
Clicking the 'go' button once more will move it to the next corner (top-left, which is the start).
I've included a picture to show exactly what I mean by this:
What the program should do!
So, this is what I've got so far:
$(document).ready(function () {
$('#go').click(function(){
var dest = parseInt($('#block').css('margin-left').replace('px', '')) + 100;
if (dest > 0) {
$('#block').animate({
marginLeft: '1800px'
}, 0 );
}
else {
$('#block').animate({
marginLeft: dest + 'px'
}, 0 );
}
});
});
#block {
width: 100px;
height: 100px;
background: red;
margin: 0px;
top: 0px;
left: 0px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="block"></div>
<button id="go">» Run</button>
I've got the box to move to the top-right corner but cannot figure out how to make it now move down using the same button.
I've tried something with a toggle but it did not work. That looked something like this:
$(document).ready(function () {
$('#go').click(function(){
var toggle = 1
if (toggle == 1){
$("#block").animate({left: "80px"});
toggle = 0;
} else{
$("#block").animate({right: "80px"});
toggle = 1;
}
});
I was thinking of maybe using cases to switch between which coordinates the button will move the box to. However, I have no knowledge of how this works with jquery and the animate function.
If anyone has any other ideas or knows how to use the case switches in this scenario, I would really appreciate it and thank you in advance!
P.S. I've tried searching this answer on here for a couple of hours now and have not found much that will help me. I am hoping this question will serve to help others who are having a similar problem to mine!
Please try this example:
$(document).ready(function () {
var leftValue = window.innerWidth - 115; // 115 is a temp value
var topValue = window.innerHeight - 115;
var actionNum = 0;
var movingBlock = $('#block');
$('#go').click(function () {
if (actionNum < 4) {
actionNum++;
} else {
actionNum = 1;
}
switch (actionNum) {
case 1:
// move to the top right
movingBlock.animate({
left: leftValue + 'px',
top: 0
}, 1000);
break;
case 2:
// move to the bottom right
movingBlock.animate({
left: leftValue + 'px',
top: topValue + 'px'
}, 1000);
break;
case 3:
// move to the left bottom
movingBlock.animate({
top: topValue + 'px',
left: 0
}, 1000);
break;
case 4:
// move to the top left
movingBlock.animate({
left: 0,
top: 0
}, 1000);
break;
default:
break;
}
});
});
#block {
width: 100px;
height: 100px;
background: red;
margin: 0px;
top: 0px;
left: 0px;
position: relative;
z-index: 1;
}
#go {
z-index: 2;
position: relative;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="block"></div>
<button id="go">» Run</button>
There is a multi solution for your problem ,
So I suggest some simple solution , is that you pput position absolute to your div ,
then change (annimate) the left or top of this last after checking conditions ,
you can get top left position in Jquery using .position() funcion ,
See belwon Snippet (added , 1000 milisseconde in order to show annimation transition )
var widh_annimation = "400px";
var hieght_annimation = "100px";
$(document).ready(function () {
$('#go').click(function(){
var position = $("#block").position();
var annimation = {};
if(position.left == 0 && position.top == 0) {
annimation = { left:widh_annimation};
}else if(position.left > 0 && position.top == 0) {
annimation = { top:hieght_annimation};
}else if(position.left > 0 && position.top > 0) {
annimation = { left:"0"};
}else if(position.left == 0 && position.top > 0) {
annimation = { top:"0"};
}
$('#block').animate(annimation, 1000 );
});
});
#block {
width: 100px;
height: 100px;
background: red;
margin: 0px;
top: 0px;
left: 0px;
position:absolute;
}
#go {
position:absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="block"></div>
<button id="go">» Run</button>
I trying to do simple animation on element on page
$(window).on('scroll',function () {
if($(window).scrollTop() > 500){
$('#top-page').animate({ right: '50px' }, "slow");
}else{
$('#top-page').animate({ right: '-50px' }, "slow");
}
});
the problem in that it never go to else condition.
The scroll event fires many times during scrolling, so every time it fires a new animation is being added to animation queue. The queue grows to enormous size and you can't wait when the "right" animation would play.
To avoid this, you can use .stop() method which flushes the queue:
$(window).on('scroll', function() {
var sign = $(window).scrollTop() > 50 ? '' : '-';
$('#top-page').stop().animate({right: sign + '50px'}, "slow");
});
body {
height: 300vh
}
#top-page {
position: fixed;
top: 0;
right: -50px;
background: red
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="top-page">TOP PAGE</div>
$(window).on('scroll',function () {
//var body = document.body; // For Safari
var html = document.documentElement; // Chrome, Firefox, IE and Opera
if(html.scrollTop > 500){
$('#top-page').animate({ right: '50px' }, "slow");
}else{
$('#top-page').animate({ right: '-50px' }, "slow");
}
});
I'm trying to create a very simple 2D game where you run forward automatically and then jump at keypress to avoid obstacles along the course.
I made this so far. The only issue is that jumping "stops" the forward-motion. And if you for example hold the up button it stops the entire game and you keep flying upwards like a bird...
Can anyone give me some advice on how to fix it? I would also LOVE it if someone could guide me in how to place 1-2 random obstacles along the course and restart the game, also show total position left traveled if those obstacles are hit by the user.
My plan is to speed up the game every time you finish a course!
Thanks a lot in advance :)
<div style='' id='map'></div>
$(function(){
var unjump = function(){
$('#player').stop().animate({
bottom: '33'
});
}
var jump = function(){
$('#player').stop().animate({
bottom: '+=100'
});
setTimeout(unjump, 1000);
}
$(document).keydown(function(e) {
switch(e.which) {
case 38: // up
jump();
break;
}
});
var player = '<div id="player"></div>';
$("#map").append(player);
function run(){
var position = $('#player').position();
var width = $('#map').width();
if (position.left > width){
$("#player").css( "left", 0 );
}
$('#player').stop().animate({
left: '+=200'
});
}
run = setInterval(run, 100);
});
DEMO
the main error was in css positioning of player
css code
#player{
width:10px;
height:10px;
border:solid;
position:absolute;
bottom:0px;
}
#map{
position:relative;
}
html code
<div style='border:solid ;height:100px' id='map'></div>
js code
var interval = null;
var interval2 = null;
$(function () {
var player = '<div id="player"></div>';
$("#map").append(player);
var unjump = function () {
$('#player').stop().animate({
bottom: '0'
});
};
var jump = function () {
$('#player').stop().animate({
bottom: '+=100'
}, 500);
interval2 = setTimeout(unjump, 500);
};
$(document).keydown(function (e) {
switch (e.which) {
case 38: // up
jump();
break;
}
});
function run() {
var width = $('#map').width();
if ($('#player').position().left > width) {
$("#player").css("left", 0);
}
$('#player').stop().animate({
left: '+=10'
});
}
interval = setInterval(run, 500);
});
Try this:
https://fiddle.jshell.net/u8deLxkz/2/
Main issue was to perform run animation only if no other animation is running.
Except for that, I tidied up the code a little.
$(function(){
//No need for two separate functions, left is handled here as well
function jump(){
$('#player').animate({
bottom: '+=30',
left: '+=10'
},100).animate({
bottom: '-=30',
left: '+=10'
},100);
}
//I think keyup gives better results
$(document).keyup(function(e) {
switch(e.which) {
case 38: //up
jump();
break;
}
});
var player = '<div id="player" style="width: 50px; height: 50px; background-color: blue; position:absolute; bottom:500px;"></div>';
$("#map").append(player);
function run(){
var position = $('#player').position();
var width = $('#map').width();
$('#player').position()
console.log('pos ' + position.left + "\nwidth: " + width);
if (position.left > width){
$("#player").finish();
$("#player").css( "left", 0 );
}
//Continue with horizontal animation only if jumping is not in progress
if(!$('#player').is(':animated') ){
$('#player').animate({
left: '+=10'
},100);
}
}
var go = setInterval(run, 100);
});
I am trying to create something similar.
http://codepen.io/eka0210/pen/rjalx
Does anyone know what kind of jQuery plugin has been used in it.
It seems pretty straight forward and I can't seem to figure it out. Right now I'm using this for plugin
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
and the given js code in addition to that.
My problem is that I can't seem to make it animate to the other page.
Thanks for the response.
The animation is done via css translate , and little script controls behaviour during animation that is all , no plugins are used !
css:
html {
overflow-y: hidden;
}
html, body, #wrapper {
height: 100%;
width: 100%;
margin: 0;
}
nav {
position: fixed;
z-index: 100;
}
.main-container {
position: relative;
width: 100%;
height: 100%;
}
#wrapper {
position: absolute;
top: 0;
-webkit-transition: -webkit-transform 1.5s cubic-bezier(.8,0,.2,1);
}
.slide0 {-webkit-transform: translateY(0%);}
.slide1 {-webkit-transform: translateY(-100%);}
.slide2 {-webkit-transform: translateY(-200%);}
.slide3 {-webkit-transform: translateY(-300%);}
.slide4 {-webkit-transform: translateY(-400%);}
JS:
var slider = $('.slider'),
wrapper = $('#wrapper'),
animating = false,
current = 0,
lengthDiv = slider.length,
delay = 1500;
slider.on('click', function(e){
var anchor = $(this);
if(!animating){
animating = true;
current = anchor.parent().index();
wrapper.removeClass().addClass('slide'+current);
setTimeout(function(){
animating = false;
}, delay);
e.preventDefault();
}
});
$(document).keydown(function(e){var key = e.keyCode;if(key == 38 || key == 40)e.preventDefault();});
$(document).keyup(function(e){
if(!animating){
var key = e.keyCode;
if(key == 38 && current > 0){
$(slider[current - 1]).trigger('click');
}else if(key == 40 && current < lengthDiv - 1){
$(slider[current + 1]).trigger('click');
}
}
});
$(document).mousewheel(function(e, deltaY){
if(!animating){
if(deltaY > 0 && current > 0){
$(slider[current - 1]).trigger('click');
}else if(deltaY < 0 && current < lengthDiv - 1){
$(slider[current + 1]).trigger('click');
}
}
return false;
});
I have a JQuery function that makes a nav bar slide up or down as you scroll vertically. The idea is to always keep the navbar 20 pixels from the top of the client window. When the user scrolls up or down, the nav bar slides till it is back to 20 pixels from the top of the client window.
My Problem: It just wont bloody move lol. What have I done wrong?
Here is my JSFiddle with JQuery code: http://jsfiddle.net/wLga8/
Here is my code:
function moveDistanceEaseIn( /*HTML Element*/ ele, /*int|float*/ dist, /*Function*/ funct )
{
ele = $(ele);
var min = dist*0.01;
// kill an already running animation
if (ele.data("animInterval"))
clearInterval(ele.data("animInterval"));
var step = function()
{
if (dist <= min)
{
ele.data("animInterval", false);
clearInterval(interval);
return;
}
var stepMove = dist*0.1;
dist -= stepMove;
funct(ele, dist, stepMove);
};
var interval = setInterval(step, 30);
ele.data("animInterval", interval);
}
function moveToPointEaseIn( /*HTML Element*/ ele, /*int|float*/ curPoint, /*int|float*/ point, /*Function*/ funct, /*bool*/ signed )
{
ele = $(ele);
var dist = (signed == true) ? curPoint - point:Math.abs(curPoint - point);
moveDistanceEaseIn(ele, dist, funct);
}
$(document).ready(function()
{
$(window).scroll(function ()
{
var nav = $("#aa");
moveToPointEaseIn(nav, nav.position().top, $(window).scrollTop()+20, function(ele, dist, stepMove)
{
ele.css("top", ele.position().top+stepMove);
}, true);
});
});
And some example HTML:
<body style="height: 3000px;">
<div id="aa" style="position: absolute; left: 0px; top: 20px; width: 200px; height: 500px; background-color: red;"></div>
</body>
I'm not certain why your function isn't working. The fiddle wasn't set to use jquery, but even setting that has no effect.
However, this seems to do what you're after....
<body style="height: 3000px;">
<div id="aa" style="position: absolute; left: 0px; top: 20px; width: 200px; height: 500px; background-color: red;">
</div>
var $scrollingDiv = $("#aa");
$(window).scroll(function(){
$scrollingDiv.stop().animate({"marginTop": ($(window).scrollTop() + 0) + "px"}, 20 );
});
DEMO
Not sure if it will solve all of your problem, but these should at least get you up and running so you can debug your code further:
Add the jQuery library to your fiddle (missing in the one you posted)
The first time your step function runs, the values are negative: -100 and -1. This means your <= test will kill your animation on the first iteration
I hacked around this by changing this line:
if (dist <= min)
To this:
if (Math.abs(dist) <= Math.abs(min))
The animation still looks wrong, but at least it is animating :)
Here's the modified fiddle: http://jsfiddle.net/wLga8/4/