Search code examples
javascripttargetvarscoping

Javascript variable scope issue


I have a simple scoping issue that is eluding me.

Here is a simpler version of the code but employs the same principle.

function myFunction(){
  $('.selector_1, .selector_2').click(function(e){
    var $trgt = $(e.target);
    var myVAR;

    if ($trgt.is('.selector_1')){
      myVAR = 'selector_1';
    }

    if ($trgt.is('.selector_2')){
      myVAR = 'selector_2';
    }
    console.log(myVAR);
  }
}

The issue is, if the user were to click on selector_1 myVAR would get populated successfully every time, however, the 2nd target handler will always return myVAR as undefined.

I'm assuming this is a programming 101 type thing, I have yet to find a straightforward answer, however.

Thanks for taking a look at this! Criticism openly appreciated.


Solution

  • Your html is probably something like this:

    <div class='selector_1'>HELLO</div>
    
    <div class='selector_2'><span>HI THERE</span></div> 
    

    So when you click on the second one you get undefined bacause the target is the span and not the selector.

    Fiddle demo: http://jsfiddle.net/maniator/M6fYf/