Danny Pearson Danny Pearson - 1 year ago 34
jQuery Question

All Elements Changing on Hover Modular Jquery

I'm experimenting with modules and I'm unsure of how to change the scope of the hover event in this way. As you'd probably guessed I'd like only the image I've hovered over to change. Any help would be greatly appreciated :) It's probably going to be really obvious but I literally can't think of how to fix it.

console.log(this.$itemIcon);


returns
[img, img, img, img, prevObject: m.fn.init(4), context: document, selector: ".work-item img"]


where I'm trying to return
[img, context: img]


Here is a shortened version of my code:

(function () {

var set = {
init: function () {
this.cacheDom ();
this.bindEvents ();
},
cacheDom: function () {
this.$item = $(".work-item");
this.$itemIcon = this.$item.find("img");
},
bindEvents: function () {
this.$itemIcon.hover(growShrink.grow.bind(this), growShrink.shrink.bind(this));
},
};

var growShrink = {
grow: function() {
this.$itemIcon.animate({height: "+=10px"}, 100);
},
shrink: function() {
this.$itemIcon.animate({height: "-=10px"}, 100);
}
};

set.init ();

})();


JS Fiddle

I'm trying to make it functionally identical to this.

$(".work-item").find("img").hover(function(){

$(this).animate({height: "+=10px"}, 100);

}, function(){
$(this).animate({height: "-=10px"}, 100);
});

Answer Source

I'm guessing in short you're trying to make each image change individually. But when you do this.$item = $(".work-item"); you're telling jQuery to find all <div class="work-item" /> which is why when you hover one all of them change.

you need to do a for each loop and then bind the events

bindEvents: function() {
  this.$itemsIcons.each(function() {
    var $icon = $(this);

    $icon.hover(animations.grow.bind($icon), animations.shrink.bind($icon));
  });
},

JS Fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download