Your code looks great, except that if the variable declaration is inside the dom read handler, then it will not be a global variable ... it will be a closure variable
jQuery(function(){ //here it is a closure variable var a_href; $('sth a').on('click', function(e){ a_href = $(this).attr('href'); console.log(a_href); //output is "home" e.preventDefault(); } })
To make a global variable, one solution is to declare the variable in the global scope
var a_href; jQuery(function(){ $('sth a').on('click', function(e){ a_href = $(this).attr('href'); console.log(a_href);
another should set the variable as a property of the window object
window.a_href = $(this).attr('href')
Why console printing is undefined
You get the output as undefined , because although the variable is declared, you did not initialize it with a value, the value of the variable is set only after the a element is pressed before this time the variable will be undefined . If you do not declare a variable, it will throw a ReferenceError
Arun P Johny
source share