The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums JavaScript Same variable for multiple events?

  • This topic is empty.
Viewing 5 posts - 1 through 5 (of 5 total)
  • Author
  • #158927

    How can I use the same variable once for a set of events using jquery? Keep in mind the variable holds a dynamic value, and will update when the function executes. Think of a set of list items that change color when the selected element has the class ‘current’.

    Sample code:

    Any help is appreciated…Thank you


    What you’re currently doing is correct if the .current elements keep changing and need to be calculated when the event fires.

    You could do this:
    But then the elements current contains will remain constant.


    To answer the question, you need a globally scoped variable, or a variable within a scope. A global variable is what @jamygolden showed you in his example. The variable current is “outside” the function. You can then call this variable inside any of the functions following it.

    A better way to execute this would be to stay away from creating commonly named variables, such as “current”.

    You can create a set of instructions with a single variable, for example:

    var mySettings = {
        currentElement: 'current',
        nextElement: 'next'
    //Shorten the mySettings var to a more easier name 
    var o = mySettings;
    // Now you can call anything inside mySettings like so.
    // Some Function...
    function myFunc() {
        // Add .current to all div elements
        // if a <div> has the class .current, add the class .next
        if ($('div').hasClass(o.currentElement)) {
    // Call the function



    Thank you both for the suggestions…



    The code snippet from my original post was simply for demonstration purposes. The real code I’m working with is just over 100 lines. If you have time and I sent you the source, would you be able to suggest a way to simplify and make the code more efficient?

    thanks and happy holidays


    After further reading…i think i’ve been able to tackle this on my own. Thanks again for your previous help.

    happy new year!

Viewing 5 posts - 1 through 5 (of 5 total)
  • The forum ‘JavaScript’ is closed to new topics and replies.