Question: I have a page with some img links. When the images are in the `hover` state, I change a background of a div inside my page. The javascript code is below:

```
function hover(element) {
  if(element.id=="first"){
      element.setAttribute('src', './images/first_active_2.png');
      back.style.backgroundImage = 'url(./images/1.png)';
      text.src = './images/text_first_active.png';
  }
  if(element.id=="second"){
      element.setAttribute('src', './images/second_active_2.png');
      back.style.backgroundImage = 'url(./images/3.png)';
      text.src = './images/text_second_active.png';
  }
}

function unhover(element) {
  if(element.id=="first"){
    element.setAttribute('src', './images/first_inactive_2.png');
    text.src = './images/text_first_inactive.png';
  }
  if(element.id=="second"){
    element.setAttribute('src', './images/second_inactive_2.png');
    text.src = './images/text_second_inactive.png';
  }
}

```

and the html code:

```
<div id="back"/>
  <a>
    <img id="first" src="images/first_inactive_2.png" onmouseover="hover(this);" onmouseout="unhover(this);" />
  </a>
  <a>
    <img id="second" src="images/second_inactive_2.png" onmouseover="hover(this);" onmouseout="unhover(this);"/>
  </a>

```

Everything is good, but the fact that sometimes the background image flickers. I think I have to preloade the two `images/1.png`, `images/2.png`, but I don't know how to do it properly. Is there a correct way to have the images not flickering?

Answer: 
var img = new Image();
img.src = "/path/to/image.jpg";

This could be in a window.load or dom:ready event somewhere and this way you could preload an image.
Use css `:hover` and [preload](http://jsfiddle.net/frontenddeveloping/qbr35/) hover image in `:after` pseudo-element:

```
div {
    background: url(http://keddr.com/wp-content/uploads/2013/12/google.png);
    width:300px;
    height: 200px;
    background-size: 100% 100%;
}

div:after {
    content: '';
    font: 0/0 a;
}

div:hover,
div:after {
    background-image: url(http://hi-news.ru/wp-content/uploads/2013/11/0111.jpg);
}

```