Random background image using jQuery for Elementor and Wordpress

Viewed 969

Trying to load a new background image on page refresh using jQuery. Spent hours on it and can't get it to work. In my child theme I have a folder for my images and a separate js folder.

I've got a full-height Elementor section with an ID of #background.

My js file:

$(document).ready(function() {
  var images = new Array('absolute path to images/bg_01.png', 
   'https://absolute path to images/bg_02.png', 
   'absolute path toimages/bg_03.png');
  var num = Math.floor(Math.random() * images.length);
  $("#background").css('backgroundImage', 'url(' + images[num] + ')');
});

Child theme functions.php:

function load_js_assets() {
  if( is_page( ID ) ) {
    wp_enqueue_script('my-js', 'absolute path to /js/myscript.js', array('jquery'), '', false);
  } 
}

add_action('wp_enqueue_scripts', 'load_js_assets');

Where might I be going wrong?

Something to add in the header.php? footer.php?

1 Answers

Change

$("#background").css('backgroundImage', 'url(' + images[num] + ')');

to

$("#background").css('background-image', 'url(' + images[num] + ')');
Related