twan
twan

Reputation: 2659

Changing CSS of one element using jQuery not working

I have a couple of elements that I want to change the grayscale of when hovering. Instead of changing all of them at the same time (since they have the same class) I only want to change the one that is currently being hovered.

So I made the following code:

tpj(".cftoverlay").hover(function(){
    tpj(this).find(".hoverBorderWrapper > img").css("filter","grayscale(0%)");
    console.log("test");
},function() {
    tpj(this).find(".hoverBorderWrapper > img").css("filter","grayscale(100%)");
    console.log("test1");
});

The console log works but for some reason the rest of the code doesn't. What am I doing wrong?

My html structure:

<span class="cftoverlay">
    <img src="images/overlay.png">
</span>
<span class="hoverBorderWrapper">
    <img width="750" height="350" src="cms/images/afbeeldingen/artikelen/IMG-20170208-WA0021.jpg" class="img-responsive big-featuredarticles" alt="css3panels-alt-04" title="css3panels-alt-04">
    <span class="theHoverBorder"></span>
</span>

The image stays grayscale no matter what since I added some css so it's grayscale when not hovered, but inline css added by jquery should always overwrite that right?

When hovering it, I can see something changing in my element inspector on this line:

<span class="cftoverlay">

But no css is added anywhere.

Upvotes: 1

Views: 104

Answers (2)

MickRip
MickRip

Reputation: 372

Instead of using jQuery, use pure CSS.

eg.

<img src="images/foo.jpg" class="hoverBorderWrapper"/>

<style>
    .hoverBorderWrapper{
        -webkit-filter: grayscale(100%);
        filter: grayscale(100%);
     }

    .hoverBorderWrapper:hover{
        -webkit-filter: grayscale(0%);
        filter: grayscale(0%);
     }
</style>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

I'm assuming that tpj is a reference to jQuery. If so, your issue is because .hoverBorderWrapper is not a child of .cftoverlay but a sibling instead. You need to use next() to retrieve it instead of find():

tpj(".cftoverlay").hover(function(){
    tpj(this).next(".hoverBorderWrapper > img").css("filter", "grayscale(0%)");
    console.log("test");
}, function() {
    tpj(this).next(".hoverBorderWrapper > img").css("filter", "grayscale(100%)");
    console.log("test1");
});

That said, I'd not use JS for this at all. CSS is more better suited to styling changes under the hover event:

.hoverBorderWrapper > img {
  filter: grayscale(100%)
}
.cftoverlay:hover + .hoverBorderWrapper > img {
  filter: grayscale(0%)
}

Upvotes: 3

Related Questions