Home Display random image when page loads with associated text title
Reply: 0

Display random image when page loads with associated text title

user1514
1#
user1514 Published in April 21, 2018, 3:29 pm

I'm trying to create a fairly simple piece of JavaScript that displays a random image from an array each time the page loads and then an associated block of text as a title to each picture. I need to figure out a way to get this running without adding code to the body tag. Is there a way to accomplish this without, say, an onload function placed in the body tag?

Here's what I have that relies on the onLoad:

<html>
<head/>
<title>Test</title>
<script type="text/javascript">
  var imageUrls = [
       "http://ww.example.com/image-01.jpg"
     , "http://ww.example.com/image-02.jpg"
     , "http://ww.example.com/image-03.jpeg"
  ];
 var imageLinks = [
       "http://ww.example.com/yoga/"
     , "http://ww.example.com/self-hypnosis/"
     , "http://ww.example.com/herbalism/"
  ];
 var imageText = [
       "Click here to enjoy your Yoga class."
     , "Click here to enjoy your Self-Hypnosis class."
     , "Click here to enjoy your Herbalism class."
  ];

  function getImageHtmlCode() {
    var dataIndex = Math.floor(Math.random() * imageUrls.length);
    var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';        
    img += imageUrls[dataIndex];
    img += '\" alt=\"Some alt text\"/></a>';
    return img;
  }
</script>
</head>
<body bgcolor="white">
<script type="text/javascript">
  document.write(getImageHtmlCode());
</script>
</body>
</html>
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.324647 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO