I have a question concerning style/compactness. I have a function which I want to run once when my document loads, and also whenever an event is triggered.
My code looks something like this:
$('.myClass').each(function(){my_function(etc);});
$('.myClass').keyup(function(){my_function(etc);});
I’m wondering if there is a way to combine these two lines of code into one. It works fine at present, but the fact that I’m repeating code has me thinking that there could be a more succinct way to do this.
.bind() and .on() gave me no joy. I am assuming this is because they’re intended for events, and .each() isn’t an event.
Can anybody offer any insight? Cheers
So, http://api.jquery.com/jQuery.each/ is iterator
The $.each() function is not the same as $(selector).each(), which is used to iterate, exclusively, over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is a map (JavaScript object) or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time. (The value can also be accessed through the this keyword, but Javascript will always wrap the this value as an Object even if it is a simple string or number value.) The method returns its first argument, the object that was iterated.
keyupis event: http://api.jquery.com/keyup/Hope it fits the cause and lemme know if I missed anything!
:)Try this: