SamYoungNY
SamYoungNY

Reputation: 6624

Best way to change CSS Background Image on hover

I have a Full-Screen Background image that I need to swap out for other images when hovering over a div. I'm doing this with jQuery - the problem is there's a fairly significant load time.

Is there a way to structure this so that the image appears near-instantaneously on the first hover? Code I have below:

$("#hover-bg-2").mouseover(function() {
  $("#container").css("background", "url(/assets/image-2.jpg)");
  $("#container").css("-webkit-background-size", "cover");
  $("#container").css("-moz-background-size", "cover");
  $("#container").css("-o-background-size", "cover");
  $("#container").css("background-size", "cover");
});
#container {
  width: 100vw;
  height: 100vh;
  
  /* ORIGINAL IMAGE BEFORE CHANGE */
  background: url(/assets/image-1.jpg) no-repeat center center fixed;
  
  -webkit-background-size: cover;
  -moz-background-size: cover;
  -o-background-size: cover;
  background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">
  <div class="bg-hover">
    <div id="hover-bg-2" style="cursor: pointer;">
      <p>BG 2</p>
    </div>
  </div>
</div>

Upvotes: 0

Views: 3699

Answers (3)

Akshay Hegde
Akshay Hegde

Reputation: 16997

You can change the class of your container using mouse events, load css initially, just change class of your container using Jquery

For example :

$("#hover-bg-2").hover(function() {
  $('#container')
    .removeClass("class_default")
    .addClass("other");
}, function() {
  $('#container')
    .removeClass("other")
    .addClass("class_default");;
});
.class_default {
  /* your style goes here */
  background: red;
}
.other{
background:green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container" class="class_default">

  <div class="bg-hover">
    <div id="hover-bg-2" style="cursor: pointer;">
      <p>BG 2</p>
    </div>

  </div>

Upvotes: 0

Gwellin
Gwellin

Reputation: 484

Link Prefetching in your <head> is the easiest way to reduce the loading time, no matter what swapping method you use method.

<link rel="prefetch" href="/images/big.jpeg">

I'm not sure why Safari doesn't support this, but the other browsers do.

Upvotes: 1

Alex
Alex

Reputation: 105

You can do this in CSS3 (most browsers should support this by now). It also will have the advantage of working even if javascript wont.

You can do this with this:

.classToChange{
    background: "oldbackground.jpg"
}

.classToHoverOver:hover .classToChange{
      background: "newbackground.jpg"
}

Upvotes: 1

Related Questions