0

I'm having a hard time finding the solution for this for some reason -- perhaps it's right under my nose.

But is there a way to essentially combine a string and an object so I'm not repeating the same method on a certain event?

$j(window).resize(function(){
  //stuff here
});

$j('body').resize(function(){
  //same stuff here
});

Maybe I'm just thinking about it the wrong way?

Thanks.

4 Answers 4

2

You can add any selector to another with .add

E.g.:

$j(window).add('body').resize(function(){
  //same stuff here
});
Sign up to request clarification or add additional context in comments.

1 Comment

Upon testing, this seems to be the best solution. Thanks!
2

Assign the function to a variable.

var handler = function(){
  //stuff here
};

$j(window).resize(handler);

$j('body').resize(handler);

Or pass an Array of the DOM elements like this:

$j([window, document.body]).resize(function(){
      //stuff here
});

3 Comments

+1 I was surprised this wasnt mentioned before! Unnamed functions are good to have, but if you are going to use the identical function twice then give it a name, dont declare an unnamed function twice.
The second answer is good, but before I give you a check, can you answer if I can pass in a mixed array, one with a jQuery object and window? [window, $j('soandso)]
@jel402 - For the jQuery object, you would need to extract the DOM element like this: $j('soandso)[0] (assuming there's only one element in there).
1

Try this:

$("body").add(window).resize(function(){
   //stuff here
});

Comments

0

I think you are talking about javascript reserverd words. You have list here.

http://www.quackit.com/javascript/javascript_reserved_words.cfm

1 Comment

Not quite. I'm working with legacy code, and for some reason they have the same bind, one on the window object (which I do know is a reserved word -- we intentionally call it) and one on the DOM element body.

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.