Search
 
SCRIPT & CODE EXAMPLE
 

JAVASCRIPT

set an attribute background image javascript

function bg() {

   var imgCount = 3;
   var dir = 'http://local.statamic.com/_themes/img/';
   // I changed your random generator
  	//floor: helps getting a random integer
   var randomCount = (Math.floor(Math.random() * imgCount));
   // I changed your array to the literal notation. The literal notation is preferred.
   var images = ['001.png', '002.png', '003.png'];
   // I changed this section to just define the style attribute the best way I know how.
   document.getElementById('banner').setAttribute("style", "background-image: url(" + dir + images[randomCount] + ");background-repeat: no-repeat;background-size: 388px 388px");
}
// Don't forget to run the function instead of just defining it.
bg();
Comment

set background image javascript

//Dynamically set the background image using js

let imageLink = 'https://images.pexels.com/photos/3928264/pexels-photo-3928264.jpeg?auto=compress&cs=tinysrgb&w=600&lazy=load'
document.getElementById(
    'body'
  ).style.backgroundImage = `url(${imageLink})`;
//Note that the url is encompassed by backticks, not single quotations.
//Backticks can be gotten on keyboard 
//You can build a function and make imageLink a parameter or do anything else. 
//There are many thinngs
Comment

PREVIOUS NEXT
Code Example
Javascript :: datatable without pagination 
Javascript :: moment js difference between start and end in hours 
Javascript :: hide div js 
Javascript :: change object key name javascript es6 
Javascript :: javascript object to json 
Javascript :: js scroll page horizontally with mouse wheel 
Javascript :: how to access xpath in js 
Javascript :: day name date js 
Javascript :: add value to the top of an array in js 
Javascript :: odd even condition with ternary operator in javaScript 
Javascript :: change background image through props 
Javascript :: angular delete from array by name 
Javascript :: how to store array into react-native local storage 
Javascript :: js replace all spaces 
Javascript :: defer parsing of javascript wordpress 
Javascript :: How can I refresh a page with jQuery 
Javascript :: js format urcurency 
Javascript :: javascript redirect to url 
Javascript :: javascript redirect new window 
Javascript :: select a random element from from items array 
Javascript :: server express node js 
Javascript :: javascript prompt 
Javascript :: javascript clear classlist 
Javascript :: change event listener in javascript 
Javascript :: react get current date yyyy-mm-dd 
Javascript :: validatorjs get all errors 
Javascript :: howt to disable a select tag using js 
Javascript :: json fetch data doest show 
Javascript :: loopback upsert with where 
Javascript :: object to query string js 
ADD CONTENT
Topic
Content
Source link
Name
2+7 =