Jakedk
Jakedk

Reputation: 101

Change background image on hover and keep active

I'm new to all this and was hoping for some help. I want the background to stay after you hover one of the links. Also is it possible to make a fade/transition on the background when appearing?

$(document).ready(function() {
    
    $('#change').hover(function() {
        $('body').css('background-image', 'url("http://i.imgur.com/cyxXVpT.jpg")');
    }, function() {
        $('body').css('background', '');
    });
    
    $('#change2').hover(function() {
        $('body').css('background-image', 'url("http://i.imgur.com/5MupbQ2.jpg")');
    }, function() {
        $('body').css('background', '');
    });
});
body {
    background-repeat: repeat;
    background-size:cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<a href="#" id="change">Change</a>
<br>
<a href="#" id="change2">Change2 </a>

Upvotes: 1

Views: 615

Answers (2)

Vincent
Vincent

Reputation: 743

If you want keep the background don't use the 2nd parameter of hover function The first parameter of over is when you hover the object and the second on blur. https://api.jquery.com/hover/ It's possible to fade in using animate function https://api.jquery.com/animate/

EDIT: or a transition with css like adeneo said

Upvotes: 0

adeneo
adeneo

Reputation: 318182

If you want the background to stay, just use the mouseenter event only

$('#change').on('mouseenter', function() {
    $('body').css('background-image', 'url("http://i.imgur.com/cyxXVpT.jpg")');
});

If you want fading backgrounds, you can use css transitions

-webkit-transition: background ease-in 1s;
-moz-transition: background ease-in 1s;
-o-transition: background ease-in 1s;
transition: background ease-in 1s;

FIDDLE

Upvotes: 1

Related Questions