Ryan King Ryan King - 1 month ago 7
Javascript Question

Custom jQuery method act independently on each instance of an element

I've created a method that makes a black bar appear on the side of an image on mouseover. It's all well and good when it's only one image but when applied to multiple images the black bar appears on both images in the event of mouse over.

Is it possible to to get each image to act independently from each other so that the mouseover event only activates the black bar for that particular image?




jsFiddle - http://jsfiddle.net/7kw8z/11/




I call the method via
$("img.edit").panzoom();


And This is the method:

!function($){


$.fn.panzoom = function() {
var $this = $(this);
this.imagesLoaded(function(){

$this.wrap('<div class="img_wrapper" />');

var imgEl = $this.parent(".img_wrapper");

imgEl.width($this.width());
imgEl.height($this.height());
//imgEl.offset({top:$this.offset().top,left:$this.offset().left});

imgEl.append('<div class="img_menu" />');
menuEl = imgEl.children(".img_menu");


imgEl.hover(function() {
$(menuEl).css("visibility", "visible");
}, function() {
$(menuEl).css("visibility", "hidden");
});

});
}

}(window.jQuery);

Answer

you can do

$.fn.panzoom = function() {
return this.each(function(){
    var $this = $(this);
    $this.imagesLoaded(function(){
        $this.wrap('<div class="img_wrapper" />');

        var imgEl = $this.parent(".img_wrapper");

        imgEl.width($this.width());
        imgEl.height($this.height());

        imgEl.append('<div class="img_menu" />');
        var menuEl = imgEl.children(".img_menu");

        imgEl.hover(function() {
            menuEl.css("visibility", "visible");
        },  function() {
            menuEl.css("visibility", "hidden");
        });
    });
});
}     

http://jsfiddle.net/7kw8z/21/