0

So I have the following fragment:

 $(".server").each(function() {
     var element = $(this);
      //bunch of javascript here with element
 });

I also want to bind a single click event for an id to do the same work as the above, how is this possible, without copying and pasting the entire block and doing:

 $("#my-id").click(function() {
       var element = $(this);
      //bunch of javascript here with element
 });

1 Answer 1

7

I think the following should work:

var eventHandler = function() {
    var element = $(this);
    //bunch of javascript here with element
};

$(".server").each(eventHandler);
$("#my-id").click(eventHandler);
Sign up to request clarification or add additional context in comments.

2 Comments

Will the $(this) work though in this case if I use an external function?
I believe it should, simplest way to check would be to give it a try ;)

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.