Subtract from an integer using jquery

I want to scroll to a div each time user presses j key. Here is the code for it.

$(function() {
    function scroll(direction) {

        var scroll, i,
                positions = [],
                here = $(window).scrollTop(),
                collection = $('.message_box');

        collection.each(function() {
            positions.push(parseInt($(this).offset()['top'],0));
        });

        for(i = 0; i < positions.length; i++) {
            if (direction == 'next' && positions[i] > here) { scroll = collection.get(i); break; }
            if (direction == 'prev' && i > 0 && positions[i] >= here) { scroll = collection.get(i); break; }
        }

        if (scroll) {
        $('html, body').animate({"scrollTop": $(scroll).offset().top-50});
            $(scroll).css('color', 'blue');
            $(scroll).mouseleave(function() {
            $(this).css('color', 'black');
            });
        }

        return false;
    }

    $("#next,#prev").click(function() {        
        return scroll($(this).attr('id'));        
    });
$('body').keyup(function(event) {
  if (event.which == 74) {
     return scroll('next');
   }
});
$('body').keyup(function(event) {
  if (event.which == 75) {
     return scroll('prev');
   }
});

});

I need to subtract 50 from the offest of the div to scroll to which is this.

$('html, body').animate({"scrollTop": $(scroll).offset().top-50});

It will scroll the first time but not the rest of the times. I always get the integer 218 which is the offset of the first div to scroll to. DEMO - http://jsfiddle.net/XP5sP/6/ Can someone help me ?

Answers:

Answer

The problem is that you're always moving the scrollTop value to 50 pixels before the first matched element, so it's always identifying that element as the one you need to scroll to in your if statement because its position is greater than the current scrollTop value.

Modify the relevant section of your code to this:

if (direction == 'next' && positions[i] > here + 50) {
    scroll = collection.get(i);
    break;
}

That way it accounts for the window being scrolled to 50 pixels above the current element.

Answer

$(scroll).offset().top-50 is prefectly valid, as .top will return an integer value. Therefore the issue is not with this portion of your code.

I suspect the issue is to do with the scroll variable you have within the scroll function. I always keep away from naming my variables the same as my function names when within the same scope.

Answer

Try putting some space between your minus symbol so it does not get mistaken for a dash.

$('html, body').animate({"scrollTop": $(scroll).offset().top - 50});

or save your mathematics in a variable first

var scrollMinusFifty = $(scroll).offset().top - 50;
$('html, body').animate({"scrollTop":scrollMinusFifty});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.