Baz Baz - 23 days ago 5x
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:

$(document).ready(function() {

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

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

// 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', '');


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 :),

  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 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 ( === cand) { = "url('')";
    } else if ( === rec) { = "url('')";
    } else { //If none match, remove bg image and show default background. = "";

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


.preload {
  <image class="preload" src=""/>
  <image class="preload" src=""/>
  <div class="container">
    <button id="cand">Candidate</button>

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