0

In working to transition an image from grayscale to full color after a fixed time I encountered a problem with Jquery's interaction with CSS Transition and i'm not sure what the work around is supposed to be:

If I start out with the existing #globecont img { style and change the .globefc from a class to a #globefc:hover everything works fine. But when I use Jquery to apply it as a class after a delay - the "class" is added to the IMG properly, but no transition or change in the filter is occurring.

I have not yet tried using .trigger("hover") in place of .addClass() but regardless of if that works or not, can someone explain why this doesn't work as written?

JS Fiddle Here

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<style>
body {background-color:#000000;}
#globecont {position:relative; margin-left:auto; margin-right:auto; text-align:center;}
#globecont img {
    filter: grayscale(100%);
    -webkit-filter: grayscale(100%);
    transition: 3s;

}

.globefc {
    filter: grayscale(0%);
    -webkit-filter: grayscale(0%);
    filter: none;
    }
</style>
</head>

<body>
<div id="globecont"><img src="http://philanthropicsandbox.org/wp-content/uploads/2012/12/Globe1.png" width="300" height="300" id="globe"></div>
<script>
$(document).ready(function() {
    $('#globe').delay(500).addClass("globefc");

    });
</script>
</body>
</html>
1
  • On a side note to any future readers: I realized after the fact that .delay() can't be used with addClass() as .delay() only applies to animation effects, it will have to be setTimeout() instead. Commented Oct 9, 2015 at 17:59

1 Answer 1

2

The problem is, #globecont img is a more specific selector then .globefc, meaning it overrides the style added by .globefc, even though it is further down the stylesheet.

You can fix this by making the second selector more specific:

#globe.globefc {
    filter: grayscale(0%);
    -webkit-filter: grayscale(0%);
    filter: none;
    }

JSFiddle Demo

Note: In your html, you already had the class .globefc added to the image, so the jQuery didn't actually do anything. In the JSFiddle, I removed that class, since it is added 500ms later by the jQuery.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, didnt really think about CSS precedence playing a role here, but i get it now. Thanks! Will accept answer as soon as it lets me
@DMSJax you will run into these problems a lot if you use css :D one of the easiest ways to tell is to use the browsers inspector

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.