[javascript] jQuery make global variable

How to pass function a_href = $(this).attr('href'); value to global a_href, make a_href="home"

var a_href; 

    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }

console.log(a_href);  
//Output is undefined 

This question is related to javascript jquery

The answer is


Your code looks fine except the possibility that if the variable declaration is inside a 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 the variable global, one solution is to declare the variable in global scope

var a_href;
jQuery(function(){
    $('sth a').on('click', function(e){
        a_href = $(this).attr('href');

          console.log(a_href);  
         //output is "home"

        e.preventDefault();
    }
})

another is to set the variable as a property of the window object

window.a_href = $(this).attr('href')

Why console printing undefined

You are getting the output as undefined because even though the variable is declared, you have not initialized it with a value, the value of the variable is set only after the a element is clicked till that time the variable will have the value undefined. If you are not declaring the variable it will throw a ReferenceError


set the variable on window:

window.a_href = a_href;

You can avoid declaration of global variables by adding them directly to the global object:

(function(global) {

  ...

  global.varName = someValue;

  ...

}(this));

A disadvantage of this method is that global.varName won't exist until that specific line of code is executed, but that can be easily worked around.

You might also consider an application architecture where such globals are held in a closure common to all functions that need them, or as properties of a suitably accessible data storage object.


Questions with javascript tag:

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax Drag and drop menuitems Is it possible to execute multiple _addItem calls asynchronously using Google Analytics? DevTools failed to load SourceMap: Could not load content for chrome-extension TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app What does 'x packages are looking for funding' mean when running `npm install`? SyntaxError: Cannot use import statement outside a module SameSite warning Chrome 77 "Uncaught SyntaxError: Cannot use import statement outside a module" when importing ECMAScript 6 Why powershell does not run Angular commands? Typescript: No index signature with a parameter of type 'string' was found on type '{ "A": string; } Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop Push method in React Hooks (useState)? JS file gets a net::ERR_ABORTED 404 (Not Found) React Hooks useState() with Object useState set method not reflecting change immediately Can't perform a React state update on an unmounted component UnhandledPromiseRejectionWarning: This error originated either by throwing inside of an async function without a catch block Can I set state inside a useEffect hook internal/modules/cjs/loader.js:582 throw err How to post query parameters with Axios? How to use componentWillMount() in React Hooks? React Hook Warnings for async function in useEffect: useEffect function must return a cleanup function or nothing FATAL ERROR: Ineffective mark-compacts near heap limit Allocation failed - JavaScript heap out of memory in ionic 3 How can I force component to re-render with hooks in React? What is useState() in React? How to call loading function with React useEffect only once Objects are not valid as a React child. If you meant to render a collection of children, use an array instead How to reload current page? Center content vertically on Vuetify Getting all documents from one collection in Firestore ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment How can I add raw data body to an axios request? Sort Array of object by object field in Angular 6 Uncaught SyntaxError: Unexpected end of JSON input at JSON.parse (<anonymous>) Axios Delete request with body and headers? Enable CORS in fetch api Vue.js get selected option on @change Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) Angular 6: How to set response type as text while making http call

Questions with jquery tag:

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.? How to solve 'Redirect has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header'? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) Only on Firefox "Loading failed for the <script> with source" How to prevent page from reloading after form submit - JQuery Vue component event after render How to use jQuery Plugin with Angular 4? How to disable a ts rule for a specific line? Bootstrap 4 File Input How to force reloading a page when using browser back button? Datatables Select All Checkbox Unable to preventDefault inside passive event listener Getting Error "Form submission canceled because the form is not connected" How to create multiple page app using react Set height of chart in Chart.js console.log(result) returns [object Object]. How do I get result.name? Setting and getting localStorage with jQuery JQuery: if div is visible Using OR operator in a jquery if statement Deprecation warning in Moment.js - Not in a recognized ISO format How to use aria-expanded="true" to change a css property DataTables: Cannot read property style of undefined Disable Chrome strict MIME type checking Consider marking event handler as 'passive' to make the page more responsive Cannot open local file - Chrome: Not allowed to load local resource "Uncaught TypeError: a.indexOf is not a function" error when opening new foundation project what is right way to do API call in react js? why $(window).load() is not working in jQuery? How to use JQuery with ReactJS $(...).datepicker is not a function - JQuery - Bootstrap remove first element from array and return the array minus the first element How to use a jQuery plugin inside Vue Uncaught SyntaxError: Invalid or unexpected token jquery 3.0 url.indexOf error How to redirect page after click on Ok button on sweet alert? Content Security Policy: The page's settings blocked the loading of a resource Uncaught SyntaxError: Failed to execute 'querySelector' on 'Document' Checkbox value true/false vue.js 'document.getElementById' shorthand Removing legend on charts with chart.js v2