You have to declare the variable outside the function like so
var $myvar;
$(selector).on('click',function(){
    $myvar = 'hi';
});
alert($myvar);
This happens because of the different scopes in javascript, your variable was applied to the function's scope and the alert is outside that scope and therefore unable to access it.
All you have to remember is that javascript looks up for variables not down so you can only access variables that are declared on the current level or higher here is some examples.
var level_1;
// I can access level 1
function somefunc() {
   var level_2;
   // I can access levels 1 & 2
   return function() {
      var level_3;
      // I can access levels 1, 2 & 3 
   }
}