0

I have some simple code that returns whether I'm scrolling up or down. I want to use it as a function with return, like this:

var scripts = {
getScrollDirection: function() {
    var dir;
    $(document).on('mousewheel DOMMouseScroll', function(e) {
        if(e.originalEvent.wheelDelta / 120 > 0) {
            dir = 'up';
        } else {
            dir = 'down';
        }
    });
    return dir;
}
}

When I call scripts.getScrollDirection, I get undefined. What I am doing wrong?

5
  • 1
    Setting up and event handler doesn't mean the code inside is going to run, so dir will stay undefined. Maybe you want to place the code for the function in mousewheel DOMMouseScroll? Commented Jul 9, 2015 at 16:41
  • are your codes in different js files? or located at different parts of the html document? Commented Jul 9, 2015 at 16:42
  • @SpencerWieczorek it's odd since I used similar statements before. When I add console.log inside the if/else statements, it works. I really want to avoid placing function inside mousewheel event. Commented Jul 9, 2015 at 16:44
  • @Ji_in_coding it's all in one file. Commented Jul 9, 2015 at 16:44
  • @TomekBuszewski It is not odd at all, because you have two different functions that are called at different times. Inside the callback (and after it is called) you set a value to dir. Outside the callback, and before it is called, you have not. Commented Jul 9, 2015 at 16:46

1 Answer 1

2

You declared dir, and it is automatically initialized to undefined. Then you registered a function as an event handler. Then you returned the value of dir, which is still undefined because no value has been assigned to it.


https://en.wikipedia.org/wiki/Event-driven_programming

http://cs.brown.edu/courses/cs168/f12/handouts/async.pdf

http://www.i-programmer.info/programming/theory/6040-what-is-asynchronous-programming.html

Sign up to request clarification or add additional context in comments.

1 Comment

You're right, I forgot that it will change after an event. Thanks for this!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.