Home › Forums › JavaScript › Same variable for multiple events?
- This topic is empty.
-
AuthorPosts
-
December 21, 2013 at 8:37 am #158927RuggParticipant
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
December 22, 2013 at 11:02 am #158981jamygoldenMemberWhat 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 elementscurrent
contains will remain constant.December 24, 2013 at 1:17 pm #159068JamesParticipantTo 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();
`
December 26, 2013 at 6:55 pm #159158RuggParticipantThank 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
December 28, 2013 at 1:41 am #159206RuggParticipantAfter further reading…i think i’ve been able to tackle this on my own. Thanks again for your previous help.
happy new year!
-
AuthorPosts
- The forum ‘JavaScript’ is closed to new topics and replies.