Javascript animation on scroll - javascript

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");
}
});

Related

Inconsistent Slide Animation in a JavaScript Switch

I am trying to implement a left/right sliding animation inside of a JavaScript switch statement and the animation (sliding left and right without a bounce effect and no whitespace in between images) is not consistently activating. Also, the slide animation still activates when the previous button is clicked on the first slide and when the next button is clicked on the last slide. This should not be happening. Does anyone have any thoughts? Please see the code example.
$(function() {
// USER EDITABLE CONTROLS
var content = 'img'; // accepts any DOM element - div, img, table, etc...
var showControls = true; // true/false shows/hides the slider's navigational controls
var transition = 'slide'; // supports default, fade, slide
var transitionDuration = .5; // adjust the time of the transition measured in seconds
// VARIABLE DECLARATIONS
var contentType = $(content);
var $el = $('#showcase');
var $leftArrow = '#left_arrow';
var $rightArrow = '#right_arrow';
var $load = $el.find(contentType)[0];
var slideCount = $el.children().length;
var slideNum = 1;
// PRELOADS SLIDE WITH CORRECT SETTINGS
$load.className = 'active';
// ADD SLIDER CONTROLS TO PAGE
if (showControls === true) {
$('<div id="controls">« Previous Next »</div>').insertAfter('#showcase');
$('#controls').find('#left_arrow').addClass('disabled');
}
// LOGIC FOR SLIDE TRANSITIONS
function transitions() {
switch (transition) {
// FADE TRANSITION
case 'fade':
$('.slide').stop().animate({opacity : 0}, transitionDuration*300, function(){
$('.active').stop().animate({opacity : 1}, transitionDuration*1000);
});
break;
// SLIDE TRANSITION
case 'slide':
if (slideNum > 1) {
$('.slide').stop().animate({left : -160}, transitionDuration*800, function(){
$('.active').stop().animate({left : 0}, transitionDuration*1000);
});
}
if (slideNum < slideCount) {
$('.slide').stop().animate({left : 160}, transitionDuration*800, function(){
$('.active').stop().animate({left : 0}, transitionDuration*1000);
});
}
break;
// DEFAULT TRANSITION
case 'default':
break;
}
}
// CHECKS FOR FIRST AND LAST INDEX IN THE SLIDER
function checkSlide() {
if (slideNum == 1) {
$($leftArrow).addClass('disabled');
} else {
$($leftArrow).removeClass('disabled');
}
if (slideNum == slideCount) {
$($rightArrow).addClass('disabled');
} else {
$($rightArrow).removeClass('disabled');
}
}
// NAVIGATIONAL LOGIC FOR PREVIOUS/NEXT BUTTONS
$(document).on('click', $leftArrow, function() {
if (slideNum > 1) {
var counter = $('.active').index();
counter--;
$('.active').addClass('slide');
$('.active').removeClass('active');
transitions();
$el.find(contentType).eq(counter).addClass('active');
slideNum--;
checkSlide();
}
})
$(document).on('click', $rightArrow, function() {
if (slideNum < slideCount) {
var counter = $('.active').index();
counter++;
$('.active').addClass('slide');
$('.active').removeClass('active');
transitions();
$el.find(contentType).eq(counter).addClass('active');
slideNum++;
checkSlide();
}
})
});
#showcase {
width: 160px;
overflow: hidden;
}
img {
width: 160px;
}
a {
color: blue;
}
.disabled {
color: red !important;
}
.slide {
display: none;
opacity: 0;
position: relative;
left: 0px;
right: 0px;
}
.active {
display: block;
opacity: 1;
position: relative;
left: 0px;
right: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="showcase">
<img class="slide" src="https://picsum.photos/458/354" />
<img class="slide" src="https://picsum.photos/458/354/?image=306" />
<img class="slide" src="https://picsum.photos/458/354/?image=626" />
</div>
As said in the comments you need to fix your conditional statements. Awhile ago you had set two click handlers - one of which is binded (and is triggered regardless of any condition) when the other handler is triggered, this caused the slide animation still activates when the previous button is clicked on the first slide and when the next button is clicked on the last slide issue.
As for the animations, see my code below. I hacked your conditions a litte. When previous is clicked, the slide is to move from left to right. When next is clicked the slide is to move from right to left. I used a flag to determine the movement it will make - see the new paramter for transition function
$(function() {
// USER EDITABLE CONTROLS
var content = 'img'; // accepts any DOM element - div, img, table, etc...
var showControls = true; // true/false shows/hides the slider's navigational controls
var transition = 'slide'; // supports default, fade, slide
var transitionDuration = .5; // adjust the time of the transition measured in seconds
// VARIABLE DECLARATIONS
var contentType = $(content);
var $el = $('#showcase');
var $leftArrow = '#left_arrow';
var $rightArrow = '#right_arrow';
var $load = $el.find(contentType)[0];
var slideCount = $el.children().length;
var slideNum = 1;
// PRELOADS SLIDE WITH CORRECT SETTINGS
$load.className = 'active';
// ADD SLIDER CONTROLS TO PAGE
if (showControls === true) {
$('<div id="controls">« Previous Next »</div>').insertAfter('#showcase');
$('#controls').find('#left_arrow').addClass('disabled');
}
// LOGIC FOR SLIDE TRANSITIONS
function transitions(impl = null) {
switch (transition) {
// FADE TRANSITION
case 'fade':
$('.slide').stop().animate({
opacity: 0
}, transitionDuration * 300, function() {
$('.active').stop().animate({
opacity: 1
}, transitionDuration * 1000);
});
break;
// SLIDE TRANSITION
case 'slide':
if (impl == "next") {
$('.slide').css("left", '160px');
$('.slide').stop().animate({
left: 160
}, transitionDuration * 800, function() {
$('.active').stop().animate({
left: 0
}, transitionDuration * 1000);
});
} else if (impl == "prev") {
$('.slide').css("left", '-160px');
$('.slide').stop().animate({
left: -160
}, transitionDuration * 800, function() {
$('.active').stop().animate({
left: 0
}, transitionDuration * 1000);
});
}
break;
// DEFAULT TRANSITION
case 'default':
break;
}
}
// CHECKS FOR FIRST AND LAST INDEX IN THE SLIDER
function checkSlide() {
if (slideNum == 1) {
$($leftArrow).addClass('disabled');
} else {
$($leftArrow).removeClass('disabled');
}
if (slideNum == slideCount) {
$($rightArrow).addClass('disabled');
} else {
$($rightArrow).removeClass('disabled');
}
}
// NAVIGATIONAL LOGIC FOR PREVIOUS/NEXT BUTTONS
$(document).on('click', $leftArrow, function() {
if (slideNum > 1) {
var counter = $('.active').index();
counter--;
$('.active').addClass('slide');
$('.active').removeClass('active');
transitions('prev');
$el.find(contentType).eq(counter).addClass('active');
slideNum--;
checkSlide();
}
})
$(document).on('click', $rightArrow, function() {
if (slideNum < slideCount) {
var counter = $('.active').index();
counter++;
$('.active').addClass('slide');
$('.active').removeClass('active');
transitions('next');
$el.find(contentType).eq(counter).addClass('active');
slideNum++;
checkSlide();
}
})
});
#showcase {
width: 160px;
overflow: hidden;
}
img {
width: 160px;
}
a {
color: blue;
}
.disabled {
color: red !important;
}
.slide {
display: none;
opacity: 0;
position: relative;
left: 0px;
right: 0px;
}
.active {
display: block;
opacity: 1;
position: relative;
left: 0px;
right: 0px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="showcase">
<img class="slide" src="https://picsum.photos/458/354" />
<img class="slide" style="left: 160px;" src="https://picsum.photos/458/354/?image=306" />
<img class="slide" style="left: 160px;" src="https://picsum.photos/458/354/?image=626" />
</div>

JQuery animate top and left same time (jumping & running)

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);
});

Can't clearInterval on animation

I have some problem with this code, in this case i set div as a button, when I click the button everything is working as expected but when I want to stop animation with clearInterval it doesn’t work, just keeps looping... What I am doing wrong?
var timeout;
var d1=$(".drum1");
function dani1(){
d1.animate({height:'150px', width:'150px', opacity:'0.4'},"slow");
d1.animate({height:'100px', width:'100px',opacity:'0.8'},"fast");
}
d1.click(function(){
if (!timeout){
timeout = setInterval(dani1, 200);
} else {
clearInterval(timeout);
timeout = null;
}
});
<div class="drum1" style="background:#98bf21;height:100px;width:100px;position:absolute;">
</div>
You do not need setInterval at all..
var d1 = $(".drum1").data('end', true);
function dani1() {
if (d1.data('end'))
return d1.stop(true, true);
d1.animate({
height: '150px',
width: '150px',
opacity: '0.4'
}, "slow")
.animate({
height: '100px',
width: '100px',
opacity: '0.8'
}, "fast", dani1);
}
d1.click(function() {
if (!d1.data('end'))
d1.data('end', true);
else {
d1.data('end', false);
dani1();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="drum1" style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
The problem is your usage of setInterval(), it will queue a lot of animations every 200ms so even after clearing the interval there are a lot of animations present in the animation queue.
One easy solution is to clear the animation queue also
var timeout;
var d1 = $(".drum1");
function dani1() {
d1.animate({
height: '150px',
width: '150px',
opacity: '0.4'
}, "slow");
d1.animate({
height: '100px',
width: '100px',
opacity: '0.8'
}, "fast");
}
d1.click(function() {
if (!timeout) {
timeout = setInterval(dani1, 200);
} else {
d1.stop(true, true)
clearInterval(timeout);
timeout = null;
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="drum1" style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>
Without interval
var play;
var d1 = $(".drum1");
function dani1() {
d1.animate({
height: '150px',
width: '150px',
opacity: '0.4'
}, "slow");
d1.animate({
height: '100px',
width: '100px',
opacity: '0.8'
}, "fast");
return d1.promise();
}
d1.click(function() {
if (play) {
play = false;
d1.stop(true, true)
} else {
play = true;
anim();
}
function anim() {
dani1().done(function() {
if (play === true) {
anim();
}
})
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="drum1" style="background:#98bf21;height:100px;width:100px;position:absolute;"></div>

A close button for Lightbox_me

I've googled for a script for a close button for Lightbox_me, however all I've been able to find are scripts for bare-bones lightboxes.
(function ($) {
$.fn.lightbox_me = function (options) {
return this.each(function () {
var
opts = $.extend({}, $.fn.lightbox_me.defaults, options),
$overlay = $(),
$self = $(this),
$iframe = $('<iframe id="foo" style="z-index: ' + (opts.zIndex + 1) + ';border: none; margin: 0; padding: 0; position: absolute; width: 100%; height: 100%; top: 0; left: 0; filter: mask();"/>');
if (opts.showOverlay) {
//check if there's an existing overlay, if so, make subequent ones clear
var $currentOverlays = $(".js_lb_overlay:visible");
if ($currentOverlays.length > 0) {
$overlay = $('<div class="lb_overlay_clear js_lb_overlay"/>');
} else {
$overlay = $('<div class="' + opts.classPrefix + '_overlay js_lb_overlay"/>');
}
}
/*----------------------------------------------------
DOM Building
---------------------------------------------------- */
$('body').append($self.hide()).append($overlay);
/*----------------------------------------------------
Overlay CSS stuffs
---------------------------------------------------- */
// set css of the overlay
if (opts.showOverlay) {
setOverlayHeight(); // pulled this into a function because it is called on window resize.
$overlay.css({
position: 'absolute',
width: '100%',
top: 0,
left: 0,
right: 0,
bottom: 0,
zIndex: (opts.zIndex + 2),
display: 'none'
});
if (!$overlay.hasClass('lb_overlay_clear')) {
$overlay.css(opts.overlayCSS);
}
}
/*----------------------------------------------------
Animate it in.
---------------------------------------------------- */
//
if (opts.showOverlay) {
$overlay.fadeIn(opts.overlaySpeed, function () {
setSelfPosition();
$self[opts.appearEffect](opts.lightboxSpeed, function () {
setOverlayHeight();
setSelfPosition();
opts.onLoad()
});
});
} else {
setSelfPosition();
$self[opts.appearEffect](opts.lightboxSpeed, function () {
opts.onLoad()
});
}
/*----------------------------------------------------
Hide parent if parent specified (parentLightbox should be jquery reference to any parent lightbox)
---------------------------------------------------- */
if (opts.parentLightbox) {
opts.parentLightbox.fadeOut(200);
}
/*----------------------------------------------------
Bind Events
---------------------------------------------------- */
$(window).resize(setOverlayHeight)
.resize(setSelfPosition)
.scroll(setSelfPosition);
$(window).bind('keyup.lightbox_me', observeKeyPress);
if (opts.closeClick) {
$overlay.click(function (e) {
closeLightbox();
e.preventDefault;
});
}
$self.delegate(opts.closeSelector, "click", function (e) {
closeLightbox();
e.preventDefault();
});
$self.bind('close', closeLightbox);
$self.bind('reposition', setSelfPosition);
/*--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- */
/*----------------------------------------------------
Private Functions
---------------------------------------------------- */
/* Remove or hide all elements */
function closeLightbox() {
var s = $self[0].style;
if (opts.destroyOnClose) {
$self.add($overlay).remove();
} else {
$self.add($overlay).hide();
}
//show the hidden parent lightbox
if (opts.parentLightbox) {
opts.parentLightbox.fadeIn(200);
}
if (opts.preventScroll) {
$('body').css('overflow', '');
}
$iframe.remove();
// clean up events.
$self.undelegate(opts.closeSelector, "click");
$self.unbind('close', closeLightbox);
$self.unbind('repositon', setSelfPosition);
$(window).unbind('resize', setOverlayHeight);
$(window).unbind('resize', setSelfPosition);
$(window).unbind('scroll', setSelfPosition);
$(window).unbind('keyup.lightbox_me');
opts.onClose();
}
/* Function to bind to the window to observe the escape/enter key press */
function observeKeyPress(e) {
if ((e.keyCode == 27 || (e.DOM_VK_ESCAPE == 27 && e.which == 0)) && opts.closeEsc) closeLightbox();
}
/* Set the height of the overlay
: if the document height is taller than the window, then set the overlay height to the document height.
: otherwise, just set overlay height: 100%
*/
function setOverlayHeight() {
if ($(window).height() < $(document).height()) {
$overlay.css({
height: $(document).height() + 'px'
});
$iframe.css({
height: $(document).height() + 'px'
});
} else {
$overlay.css({
height: '100%'
});
}
}
/* Set the position of the modal'd window ($self)
: if $self is taller than the window, then make it absolutely positioned
: otherwise fixed
*/
function setSelfPosition() {
var s = $self[0].style;
// reset CSS so width is re-calculated for margin-left CSS
$self.css({
left: '50%',
marginLeft: ($self.outerWidth() / 2) * -1,
zIndex: (opts.zIndex + 3)
});
/* we have to get a little fancy when dealing with height, because lightbox_me
is just so fancy.
*/
// if the height of $self is bigger than the window and self isn't already position absolute
if (($self.height() + 80 >= $(window).height()) && ($self.css('position') != 'absolute')) {
// we are going to make it positioned where the user can see it, but they can still scroll
// so the top offset is based on the user's scroll position.
var topOffset = $(document).scrollTop() + 40;
$self.css({
position: 'absolute',
top: topOffset + 'px',
marginTop: 0
})
} else if ($self.height() + 80 < $(window).height()) {
//if the height is less than the window height, then we're gonna make this thing position: fixed.
if (opts.centered) {
$self.css({
position: 'fixed',
top: '50%',
marginTop: ($self.outerHeight() / 2) * -1
})
} else {
$self.css({
position: 'fixed'
}).css(opts.modalCSS);
}
if (opts.preventScroll) {
$('body').css('overflow', 'hidden');
}
}
}
});
};
$.fn.lightbox_me.defaults = {
// animation
appearEffect: "fadeIn",
appearEase: "",
overlaySpeed: 250,
lightboxSpeed: 300,
// close
closeSelector: ".close",
closeClick: true,
closeEsc: true,
// behavior
destroyOnClose: false,
showOverlay: true,
parentLightbox: false,
preventScroll: false,
// callbacks
onLoad: function () {},
onClose: function () {},
// style
classPrefix: 'lb',
zIndex: 999,
centered: true,
modalCSS: {
top: '100px'
},
overlayCSS: {
background: 'black',
opacity: .3
}
}
$('.trigger').click(function (e) {
$('.lightbox').lightbox_me();
e.preventDefault();
});
})(jQuery);
This is the jsfiddle with the script for Lightbox_me.
I tried to incorporate the close-button scripts for the bare-bones lightboxes into Lightbox_me, but I simply don't know where to start. Would I have to format a close button onto each of the lightboxed divs individually and simply bind closeLightbox();? Or is there a more elegant way to do it involving only the script?
By default the script has these defined:
$.fn.lightbox_me.defaults = {
// animation
appearEffect: "fadeIn",
appearEase: "",
overlaySpeed: 250,
lightboxSpeed: 300,
// close
closeSelector: ".close",
closeClick: true,
closeEsc: true,
// behavior
destroyOnClose: false,
showOverlay: true,
parentLightbox: false,
preventScroll: false,
// callbacks
onLoad: function () {},
onClose: function () {},
// style
classPrefix: 'lb',
zIndex: 999,
centered: true,
modalCSS: {
top: '100px'
},
overlayCSS: {
background: 'black',
opacity: .3
}
}
You'll notice in the close section that it defaults to looking for elements with the class "close".
So if you stick a div with that class inside your lightbox, style as you please then it will trigger the close action.
The logic for closing based on the script:
if (opts.closeClick) {
$overlay.click(function (e) {
closeLightbox();
e.preventDefault;
});
}
$self.delegate(opts.closeSelector, "click", function (e) {
closeLightbox();
e.preventDefault();
});
This part of the logic informs lightbox_me that if closeClick is true within the list of options passed to it, that it will setup clicks on the overlay to close the lightbox.
As well it will bind current and future elements with the value defined in opts.closeSelector to also initiate the closeLightbox function when clicked.
Simple example fiddle: http://jsfiddle.net/zn2hg7L8/1/

Jquery Sliding Div works only once

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;
}

Categories

Resources