Viktor Plane Viktor Plane - 7 months ago 10
Javascript Question

Swap background on hover

I'm trying to swap background using jQuery. But the problem is that it doesn't successfully switch to new background, instead, the old one is removed and I get a white background instead.

I've been googling and trying out putting the path as a var instead for example, and some other unsuccessful suggestions.

My jQuery function looks like the following:

$("#btn").hover(function () {
$('#page1').css('background-image','url(../images/bg1_normal.jpg)');
});


And my CSS for the default background looks like this:

#page1 {
height: 100vh;
max-height: 100vh;
background-image: url("../images/bg1_rw.jpg");
background-repeat: no-repeat;
background-size: 100%;
}


I'm using
Java Play Framework
and the pictures are in the same folder, and it is the correct path to it since the default background works.

EDIT: I Tried as well to use an img source from the web, just to be 100% sure it wasn't some issues with the path, but it still only makes it white.

Answer

Try .addClass and .removeClass functions - it's simple and all style work is done in stylesheet file:

$("#btn").on({
    mouseenter : function() {
        $('#page1').addClass('inverted');
    },
    mouseleave : function() {
        $('#page1').removeClass('inverted'); 
    }
});

and then simply add

#page1.inverted {
    //style as you need
}

to your stylesheet.

Comments