Commonly I bind an event with jQuery and then call it immediately afterward, such as when I set up positioning or visibility of some elements and whatnot.
$('#myElement').on('click', function () {
$('#myOtherElement').css('color', 'red');
}).click();
This works, but the pattern is a bit ugly, especially if my first selector finds multiple elements. Then the event is triggered multiple times, once for each element the first selector finds. I end up doing this instead:
$('.lots-of-elements').on('click', function () {
$('#myOtherElement').css('color', 'red');
}).first().click();
Again, this works, but it's not my favorite. Is there a better pattern to use?
I know I can do something like:
function onClick() {
$('#myOtherElement').css('color', 'red');
};
$('.lots-of-elements').on('click', onClick);
onClick();
But that's even more verbose.
onClick
handlers, ones my class doesn't know about. That's not the case yet, but theoretically, it could be. I'd have to pull my code into a new function, add the handler, and then call the function, rather than using the.click()
call. It gets more tedius.