Forums

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
    Posts
  • #158927
    Rugg
    Participant

    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: http://paste.pm/raw/cj1

    Any help is appreciated…Thank you

    #158981
    jamygolden
    Member

    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: http://paste.pm/raw/cjf
    But then the elements current contains will remain constant.

    #159068
    James
    Participant

    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
        $('div').addClass(o.currentElement);
    
        // if a <div> has the class .current, add the class .next
        if ($('div').hasClass(o.currentElement)) {
    
            $('div').addClass(o.nextElement);
    
        }
    
    }
    
    // Call the function
    myFunc();
    

    `

    #159158
    Rugg
    Participant

    Thank you both for the suggestions…

    @james

    @jamesmd

    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

    #159206
    Rugg
    Participant

    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.