0

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?

2

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

Use css :hover and preload 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);
}

Comments

0

I had a similar problem a few weeks ago. You can preload an Image using 'onload' event:

var tmpNewImg = new Image();
tmpNewImg.onload = function () {
  var yourDiv = document.getElementById('picture');
  yourDiv.style.backgroundImage = 'url(' + this.src + ')';
}

tmpNewImg.src = '/your/background/image.jpg';

This helped for my problem. But I didn't test the code in this case.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.