Hulk Hulk - 4 months ago 18
HTML Question

Same Class Name for div but hover only one at a time

I have 5

div
s with same class names called tile and I generate these
div
s dynamically. I am working on ASP.NET MVC project and based on the models I generate the tiles.

I have added the hover method for these tiles from this example using jQuery http://stackoverflow.com/a/19480774

My requirement is that, only the hovered tile need to trigger the jQuery function so that particular tile's content change. As of now all the tiles content change when I hover any one tile div.
I guess it is because all the div have same class and I am adding hover event based on the class name. Is there a small tweak in jQuery like stop propagation or should I have use id's for each div like tile-1 for each div and in some way have selectors in jQuery to add hove event?

As requested, My code is (Made changes according to answers)

$(document).ready(function () {

var wapper;
$(".tile").hover(function (e) { //mouse in
// previously had wapper = (".tile-contents-wrapper");
wapper = $(this).find(".tile-contents-wrapper");
wapper.find("div:first-child").hide();
wapper.find("div:last-child").show();
},
function (e) { //mouse out
wapper.find("div:first-child").show();
wapper.find("div:last-child").hide();
});

});


I guess it is not possible using CSS and its my mistake not to mention that I am looking for an answer using jQuery and not with CSS.

Thanks for the answers.

Answer

Your problem is that you are telling all the members of the class to change color or text. Simply change the inner part to just "this" - the hovered element

$( ".mytile" ).hover(
    function() {
        $( this ).text(  "Hover" );
    }, function() {
        $( this ).text( "No hover");
    }
 );

The JQuery hover documentation has a similar example and more information