0

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.

2
  • I think this is just you being vain, the first two examples are perfectly fine Commented Jan 21, 2016 at 21:07
  • Yes and no. On the one hand, it's mostly wanting syntactic sugar. On the other, suppose I had multiple 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. Commented Jan 21, 2016 at 21:10

1 Answer 1

0

I don't understand why you want to use a click event and then click it right away. Can't you just put the css editing in the main scope?

As to your question, you can also create a jQuery function like this:

$.fn.extend({
    clickColor: function(element, color) {
        $(this).on('click', function() {
            $(element).css('color', color);
        });
        return $(this);
    }
});

Put it in a seperate file and keep your main file clean with only:

$('#clicker').clickColor('#other', 'red').click();
$('.clicker').clickColor('.another', '#00FF00').first().click();

Have a look at the DEMO.

Ofcourse you can also put the .first() and .click() inside the function if that's what you like.

Then have a look at this DEMO 2

Sign up to request clarification or add additional context in comments.

1 Comment

The css was just a silly example. A real example would be like having a button that hides a div and shows another (toggles). When I use asp.net's UpdatePanel, the originally shown and hidden divs revert. So, I track the state, and if the user was on the originally hidden div, I trigger the click event to toggle them back to the way the user had seen before. Hope that wasn't too poorly worded.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.