Implementing JavaScript and text into a URL

66 views Asked by At

I posted before asking for a way to produce a random wallpaper from a list I had, but I was now wondering if instead of having 'images/bg-N.png' (N being a number), I could have something along the lines of this?

<script type="text/javascript">
  var images = ['1', '2', '3', '5', '6', '7', '8', '9', '10'];
  document.getElementsByClassName('mainview')[0].style.backgroundImage = 'url('"images/bg-" + images[Math.round(Math.random() * images.length)] + ".png"')';
</script>

This doesn't work, as I have very little knowledge about javascript itself. If anyone would be able to fix this for me I would be very grateful!

3

There are 3 answers

0
Weafs.py On BEST ANSWER

You don't need extra quotation marks.

<script type="text/javascript">
  var images = ['1', '2', '3', '5', '6', '7', '8', '9', '10'];
  document.getElementsByClassName('mainview')[0].style.backgroundImage = 'url(images/bg-' + images[Math.round(Math.random() * images.length)] + '.png)';
</script>
2
Jonathan Gray On

As far as I can see it's a simple syntax problem:

<script type="text/javascript">
  var images = ['1', '2', '3', '5', '6', '7', '8', '9', '10'];
  document.getElementsByClassName('mainview')[0].style.backgroundImage = "url('images/bg-" + images[Math.round(Math.random() * images.length)] + ".png')";
</script>
2
DaveAlger On

I would suggest using an integer from a range instead of an array...

var bg_min = 1;
var bg_max = 10;
var bg_url = 'images/bg-_.png';
var bg_replace = '_';
var bg_rand = Math.floor(Math.random() * (bg_max - bg_min + 1)) + bg_min;
var bg_image = bg_url.replace(bg_replace, bg_rand);

document.getElementsByClassName('mainview')[0].style.backgroundImage = "url('"+bg_image+"')";

// remove the following line in your actual page
document.getElementsByClassName('mainview')[0].innerHTML = bg_image;
<div class="mainview"></div>

for non-numeric images I would choose a random element from an array of full paths (so you can use different extensions other than .png and different locations)...

var bg_images = [
  'images/bg-1.png',
  'images/bg-2.png',
  'images/bg-3.png',
  'images/bg-4.png',
  'images/bg-5.png',
  'http://fakeimg.pl/1/ff0000/',
  'http://fakeimg.pl/2/ffff00/',
  'http://fakeimg.pl/3/00ff00/',
  'http://fakeimg.pl/4/00ffff/',
  'http://fakeimg.pl/5/0000ff/'
];

var random_bg_image = bg_images[Math.floor(Math.random()*bg_images.length)];

document.getElementsByClassName('mainview')[0].style.backgroundImage = "url("+random_bg_image+")";
<div class="mainview" style="width:300px;height:100px;"></div>