Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JQUERY onClick change 'top' attribute

Tags:

jquery

css

I am trying to create a vertical scroller using jquery and I am having troubles with my code..

function scrolldown() {     
    var newtop = $('.scroll-content').css('top') + '250';   
    $('.scroll-content').css({top: newtop});
}

The css:

.scroll-content {position:absolute; top:0px}

No problems with CSS I can change values in firebug and works fine, but the code is the issue. I want it to add 250px to current value but it doesnt work and when using .html(newtop) i can see that the output for the "top" value is 0px250… any ideas what I am doing wrong?

like image 288
Matthew Pateman Avatar asked Jul 26 '10 21:07

Matthew Pateman


3 Answers

$('.scroll-content').css('top')

will return something like "123px", which is a string (due to the "px"). If you add "250", you have "123px250", which is not what you want...

Try this one instead:

var newtop = $('.scroll-content').position().top + 250;
$('.scroll-content').css('top', newtop + 'px');
like image 131
opatut Avatar answered Sep 28 '22 05:09

opatut


You need to convert the css string ('0px') into an int (0) so you can add 250, then add the 'px' again

function scrolldown() {
  var newtop = parseInt($('.scroll-content').css('top')) + 250;
  $('.scroll-content').css({top: newtop+'px'});
}
like image 37
Ties Avatar answered Sep 28 '22 05:09

Ties


As an alternative to the posted answers, you can use a += shortcut via .animate() with no duration, like this:

$(".scroll-content").animate({ top: "+=250px" }, 0);​

This will make the change adding 250px instantly. If you actually wanted it animated, just change that 0 to a 400 for example, to get a 400ms duration.

like image 44
Nick Craver Avatar answered Sep 28 '22 06:09

Nick Craver