0

I'm trying to request a variable declared globally inside of the touchmove function but I'm getting a reference error. Does anybody know what's wrong?

function drawer(pulltab,drawer){
    $('#pulltab').on('touchstart',function(e){
        notworking=e.originalEvent.touches[0].pageX;
    })

    $(drawer).on('touchmove',function(loc){
        var fingerloc=loc.originalEvent.touches[0].pageX;
        var dist=fingerloc-notworking;
        console.log(dist);
        if (dist<0){
            $(this).css('margin-left',dist);
        }
    })

    $(drawer).on('touchend',function(){
        $(this).css('transition','margin-left .1s');
        $(this).css('margin-left',0);
    })
}
drawer('#pulltab','#navigation-drawer');
1
  • I don't see any global variable declarations in that code. Commented Feb 19, 2017 at 9:53

1 Answer 1

2

I'm trying to request a variable declared globally inside of the touchmove function

There are no global variable declarations in your quoted code.

Assuming you haven't declared it, then you are creating (but not declaring) a global variable in the touchstart handler on #pulltab:

notworking=e.originalEvent.touches[0].pageX;

That uses The Horror of Implicit Globals* to create a global. But the global won't exist until that code runs.

Clearly, your touchmove handler on drawer is firing before your touchstart handler on #pulltab. Since there is no existing global called notworking, you can't read its value, and you get a ReferenceError. If the touchstart on #pulltab had executed first, you wouldn't.

Don't rely on the horror of implicit globals. Declare your variables. If you want it to be global, put

var notworking;

...outside all functions. (Although global variables are a Bad Thing™ best avoided; if you only use notworking within the drawer function and you don't need it shared between calls to drawer, just declare it within drawer.) You might also want to check, when using it, whether it has a useful value.


* (that's a post on my anemic little blog)

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

Comments

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.