Modular Jquery Scope Issue

Modular Jquery Scope Issue
0.0 0

#1

I’m experimenting with modules and I’m unsure of how to change the scope of the hover event in this way. I’d like only the image I’ve hovered over to change but everything I try just makes every element change at the same time.

Here is a shortened version of my code:

JS Fiddle

Any help would be massively appreciated like :slight_smile:


#2

The issue is in how jQuery gathers up the target elements.

In your case, you use $itemIcon in several places, but this doesn’t target a single element, It targets all img tags contained in .work-item.

That means when you manipulate or mutate $itemIcon, you’re affecting all of those items at once.

I’d recommend looking at jQuery’s .each as part of your hover statement and then pass only the item.

This works for me:

(function () {
  
  var set = {
    init: function () {
            this.cacheDom ();
      this.bindEvents ();
    },
    cacheDom: function () {
            this.$item = $(".work-item");
            this.$itemIcon = this.$item.find("img");
    },
    bindEvents: function () {
            // switch this to `.each` so events are attached individually
            this.$itemIcon.each(function(){
              // judicious use of `$(this)` to target only the element being operated on
              $(this).hover(growShrink.grow.bind($(this)), growShrink.shrink.bind($(this)));
            })
    },
  };
    
    var growShrink = {
        grow: function() {
            // use regular `this` since we bound it up above
            this.animate({height: "+=10px"}, 100);
        },
        shrink: function() {
            this.animate({height: "-=10px"}, 100);
        }
    };
  
  set.init ();
  
})();

#3

Thank you so much man, someone literally pointed it out to me about half an hour ago :slight_smile: