Baz Baz - 2 months ago 7
CSS Question

Code to change BG image doesn't work, but can change BG color

I am trying to change the background image depending on whether the user hovers over a Candidate button or a Recruiter button.

I have tried the following code (which worked in JS Fiddle) and it fails. I inserted a background-color command (see commented line) and that worked fine so I can only assume its related to the background-image line but I can't see what I've done wrong.

The images preload fine as I can inspect them in Chrome devtools,

This is my JS Fiddle Code: http://jsfiddle.net/bdenson/m7u4vn6u/

$(document).ready(function() {




//Preload
$('<img/>').hide().attr('src', '{{url("/img/candidate.jpg")}}').on ('load',function(){
$('body').append($(this));
});

//Preload
$('<img/>').hide().attr('src', '{{url("/img/recruiter.jpg")}}').on ('load',function(){
$('body').append($(this));
});

// Change BG on Hover - candidate
$('#cand').hover(function() {
$('body').css('background-image', '{{url("/img/candidate.jpg")}}');
//$('body').css('background-color', 'red');
}, function() {
$('body').css('background', '');
});

// Change BG on Hover - recruiter
$('#rec').hover(function() {
$('body').css('background-image', '{{url("/img/recruiter.jpg")}}');
}, function() {
$('body').css('background', '');
});
});

Answer

I removed the jquery and replaced it with more modern webAPI. I hope it's okay.

This should however work pretty much anywhere unless you're using some old dino-browser :), http://jsfiddle.net/m7u4vn6u/6/

  var bod = document.getElementsByTagName('body')[0];

  var pointerPref = "pointer";

  // Check support for pointer.
  if (!window.PointerEvent && !navigator.pointerEnabled) {
    pointerPref = "mouse";
  }

  //add a eventListener for mouse movement, run mMoveFunc on movement. 
  document.addEventListener(pointerPref + "move", mMoveFunc);

  function mMoveFunc(evt) {
    //catch event (evt) on mouse movement
    //If evt.target equals one of the buttons(hovering), change bg image.
    //It finds the buttons via the id, 
    //you can do it for any html element that takes a id attribute.
    if (evt.target === cand) {
      bod.style.backgroundImage = "url('https://static.pexels.com/photos/40120/pexels-photo-40120.jpeg')";
    } else if (evt.target === rec) {
      bod.style.backgroundImage = "url('https://static.pexels.com/photos/7366/startup-photos.jpg')";
    } else { //If none match, remove bg image and show default background.
      bod.style.backgroundImage = "";
    }

  }
body {
  background-repeat: repeat;
  background-color: darkgrey;

}

.preload {
  display:none;
}
<body>
  
  <image class="preload" src="https://static.pexels.com/photos/40120/pexels-photo-40120.jpeg"/>
  <image class="preload" src="https://static.pexels.com/photos/7366/startup-photos.jpg"/>
  
  <div class="container">
    <button id="cand">Candidate</button>

    <button id="rec">Recruiter</button>
  </div>
</body>