Search code examples
jquerycssmedia-queries

Resetting the .style of an element / reverting to 'initial' without .style overriding


I have a div (.projectTitle) inside of another div (.projectContainer). When the screen is greater than 1000px wide, .projectTitle is initialized with opacity:0;. When the screen is less than 1000px wide, it is initialized with opacity:1;. See:

@media (min-width: 1000px) {
    .projectTitle {
        opacity:0;
    }
}
@media (max-width: 1000px) {
    .projectTitle {
        opacity:1;
    }
}

Now, if .projectContainer is hovered over while the screen is wider than 1000px, the opacity of .projectTitle should animate to 1, and back to 0 when unhovered. However, nothing should happen if it is hovered over when the screen is LESS than 1000px; it should alway remain at 1 in this case.

I have a variable (windowState) that changes depending on the width of the screen:

less than 1000px, windowState = 3

greater than 1000px, windowState = 2

I have a jQuery event that looks like this to handle the hovering, which does it's job properly:

$(".projectContainerr").hover(
    function(){
        if (windowState != 3){
            $('.projectTitle', this).animate({
                opacity:1},100);
        }
    },
    function(){
        if(windowState != 3){
            $('.projectTitle', this).animate({
                opacity:"initial"},100);
        }
    }
);

The Problem

When opacity is reset to it's value of initial (aka, the value as defined in the media queries) after unhovering, that value is overridden by the fact that it was already set to 1, when hovered onto. The "1" value from hovering is placed into the element's style, overriding the inherited value from the css that 'initial' has returned it to.

How do I prevent this value from overriding / reset it / animate without using the element's style?


Solution

  • Why don't you do it using css3 transition instead of jQuery

    @media (min-width: 1000px) {
      .projectContainer:hover .projectTitle{
        opacity: 1;
        transition: opacity 1s ease-in-out;
        -moz-transition: opacity 1s ease-in-out;
        -webkit-transition: opacity 1s ease-in-out;
      }
      .projectTitle {
        opacity:0;
      }
    }
    @media (max-width: 1000px) {
      .projectTitle {
        opacity:1;
    
      }
    }
    

    Here is a demo