Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

to attach an event to each element of an array

I have made several icon, and on their mouse hover they should do something. Now, I have made an array of my Icons, but as I apply each() to the set, it does not work:

So i need the following block of code to attach a hover event to each element of the set.

var icon_set = new Array('.icon-online', '.icon-save', '.icon-sms',
    '.icon-access', '.icon-support');
icon_set.each(function () {
    $(this).mouseleave(function () {
        img.stop().fadeOut();
    });
});
like image 749
Mostafa Talebi Avatar asked Jan 26 '26 06:01

Mostafa Talebi


2 Answers

Try Array.join()

var icon_set = new Array('.icon-online', '.icon-save', '.icon-sms',
    '.icon-access', '.icon-support');
$(icon_set.join()).mouseleave(function () {
    img.stop().fadeOut();
});


icon_set.each(function () { --> .each() doesn't work with array

Use jQuery.each() , array.forEach(callback[, thisArg]) for array.

like image 199
Tushar Gupta - curioustushar Avatar answered Jan 27 '26 19:01

Tushar Gupta - curioustushar


icon_set is a raw JavaScript Array. It doesn't have an each method. Use Array.prototype.forEach or $.each and wrap each array element with $();

icon_set.forEach(function (el) {
    $(el).mouseleave(function () {
        $(this).stop().fadeOut();
    });
});

or

$.each(icon_set, function(index, el) {
  $(el).mouseleave(function () {
    $(this).stop().fadeOut();
  });
});

And prefer using the array literal syntax([]) over the Array constructor

['.icon-online', '.icon-save', 
 '.icon-sms','.icon-access', '.icon-support'].forEach(yourMouseleaveHandler);
like image 45
c.P.u1 Avatar answered Jan 27 '26 19:01

c.P.u1



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!