Hai Truong IT
Hai Truong IT

Reputation: 4187

How to use jQuery mouseover from an array?

I have a sample code:

<a href=""></a>
<textarea></textarea>
<object></object>
<img src="" />
<div id="content"></div>

I had using this:

jQuery("a").mouseover(function() {
    alert();
 });
 jQuery("textarea").mouseover(function() {
    alert();
 });
 jQuery("object").mouseover(function() {
    alert();
 }); 
 jQuery("img").mouseover(function() {
    alert();
 });
 jQuery("#content").mouseover(function() {
    alert();
 });

Can I using this ?

var object = ["a","textarea","object","img", "content"]; 
jQuery.each(object, function() {
   jQuery(this).mouseover(function(){
      alert();
   });  
});

How to ideas using jQuery mouseover from an array ?

Upvotes: 2

Views: 1021

Answers (3)

Akhil Sekharan
Akhil Sekharan

Reputation: 12693

If I were you I would give a common attribute to those elements which needs the mouse over function. like a classname or a data-value attribute.
For example:

<a href="" data-hover="true"></a>
<textarea data-hover="true" ></textarea>
<object data-hover="true" ></object>
<img data-hover="true" src="" />
<div data-hover="true" id="content"></div>


<script type="text/javascript">
$(document).ready(function(){
    $('[data-hover]').bind('mouseover', function(){
        alert('Completed');
    });
});
</script>

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150070

In the context of your .each() loop, this will be the current element from the array, i.e., a string, except that each string will be wrapped in an object (as explained at the $.each() doco page), so you need to use this.toString():

jQuery(this.toString()).mouseover(function(){

...and then it will have the same effect as jQuery("a"), jQuery("textarea") and so forth. Which will work as long as each string is a valid selector. Or, better, make use of the arguments that jQuery passes to your function:

jQuery.each(object, function(i, val) {
   jQuery(val).mouseover(function(){

The final element in your array is an id, so it needs a #:

var object = ["a","textarea","object","img", "#content"];
// add # here --------------------------------^

Then in the context of the mouseover handler, this is the element that the event occurred on, so just use jQuery(this) rather than jQuery("#" + this). Putting that all together:

jQuery.each(object, function(i, val) {
   jQuery(val).mouseover(function(){
       jQuery(this).css(...);           
   });  
});​

Demo: http://jsfiddle.net/GBtFY/

Upvotes: 3

loganfsmyth
loganfsmyth

Reputation: 161497

When you access this you don't prepend #.

As for the array, I would just use a CSS selector:

$('a, textarea, object, img, #content').mouseover(function(){
  $(this).css(...);
});

Upvotes: 1

Related Questions