Reputation: 2679
I'm wondering if you can do this in jquery. I'm using version 1.10:
var myImage = $('#myImage');
What i basically want to do is assign the image as a variable so that i can use it anywhere. I want to use it during event handling:
E.g.
myImage.click(function () {
alert('Image Clicked');
});
If the above code is incorrect, I would really like to know the appropriate code.
Upvotes: 1
Views: 50
Reputation: 7442
Yes you can do it. In fact, it is recommended that you assign it to a variable so that you selector is not evaluated each time you use it. It is good for performance reasons.
Finding element by Id (such as in your case $('#myImage');
) is fast but imagine if you have a selector like
$('ul > li.myClass:has(p) a:eq(2)')
Using a variable will speed things up for you in such scenarios.
I usually use $
sign in variable name like. var $varName = $('.selector')
It helps me better understand the code and to distinguish between regular variables and variables that contain DOM elements.
Upvotes: 2