开发者

Display random image when page loads without utilizing onload in the body tag

I'm trying to create a fairly simple piece of JavaScript that displays a random image from an array each time 开发者_开发问答the page loads. 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:

    ImageSwitch=new Array();
    ImageSwitch[0]='1.jpg';
    ImageSwitch[1]='2.jpg';
    ImageSwitch[2]='3.jpg';
    ImageSwitch[3]='4.jpg';

    function swapImage() 
    {
        document.getElementById("theImage").setAttribute("src", ImageSwitch[

Math.round(Math.random()*3)])
    }

Any alternative ideas to accomplish this?


Wombleton's answer is what I would do. However, there is another way to do it. In the body markup, wherever you are going to put that random image, put a script that does a document.write with the markup for the image. Make sure you have an array of image URLs and substitute, like so:

<html>
<head>
<title>Test</title>
<script type="text/javascript">
  var imageURLs = [
       "http://www.myserver.com/images/image1.png"
     , "http://www.myserver.com/images/image2.png"
     , "http://www.myserver.com/images/image3.png"
  ];
  function getImageTag() {
    var img = '<img src=\"';
    var randomIndex = Math.floor(Math.random() * imageURLs.length);
    img += imageURLs[randomIndex];
    img += '\" alt=\"Some alt text\"/>';
    return img;
  }
</script>
</head>
<body>
<script type="text/javascript">
  document.write(getImageTag());
</script>
</body>
</html>

Again, this is not ideal, but is useful if you don't want to use any kind of onload event, not just the one you put in the <body> tag.


Adapted from jQuery's ready function, and making some assumptions about the image types:

(function() {
  var urls = ['1', '2', '3', '4'];
  function swap() {
    document.getElementById('theImage').setAttribute('src', urls[Math.round(Math.random() * urls.length)] + '.jpg');
  }

  // Mozilla, Opera and webkit nightlies currently support this event
  if ( document.addEventListener ) {
    window.addEventListener( 'load', swap, false );
  // If IE event model is used
  } else if ( document.attachEvent ) {
    window.attachEvent( 'onload', swap );
  }
})();


With a few changes this code will load images randomly and his respective link to load.

<!DOCTYPE html>
<html>
<head>
<title>Jorgesys Html test</title>
<script type="text/javascript">
  var imageUrls = [
       "http://prueba.agenciareforma.com/appiphone/android/img/newspapers/stackoverflow.png"
     , "http://ww.mydomain.com/img/newspapers/reforma.png"
     , "http://ww.mydomain.com/img/newspapers/nytimes.png"
     , "http://ww.mydomain.com/img/newspapers/oglobo.png"
     , "http://ww.mydomain.com/img/newspapers/lefigaro.png"
     , "http://ww.mydomain.com/img/newspapers/spiegel.png"
  ];
 var imageLinks = [
       "http://www.stackoverflow.com"
      , "http://www.reforma.com"
       , "http://www.nytimes.com/"
      , "https://oglobo.globo.com/"
      , "http://www.lefigaro.fr/international/"
     , "http://www.spiegel.de/international/"    
  ];

  function getImageHtmlCode() {
    var dataIndex = Math.floor(Math.random() * imageUrls.length);
    var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';        
    img += imageUrls[dataIndex];
    img += '\" alt=\"Jorgesys Stackoverflow.com\"/></a>';
    return img;
  }
</script>
</head>
<body bgcolor="white">
<script type="text/javascript">
  document.write(getImageHtmlCode());
</script>
</body>
</html>


You could place this in javascript at the bottom of the page, with a timeout.

setTimeout(swapImage, 500); or somesuch.


Just don't put you javascript inside a function.

if you take it out of the function it will run when the page loads.

When it's in the function, it won't run unless called.


You could just use document.write to generate the img tag. Or even something like <img src="javascript:Math.round(Math.random()*3)+'.jpg';" />


you don't need an onload in the body tag- add a handler in the script, in the head, or in another script that loads before the body .

(function(){
  var fun=function(){
  // definefunction
  }
  if(window.addEventListener){
      window.addEventListener('load', fun,false);
      else if(window.attachEvent)window.attachEvent('load', fun);
 })();


Your answer can be found at glados.cc/myfaucet.
there is a script for download there which has the code you are looking for here is a brief synopsis: create file config.php and put this inside:

<?php 
// Advertisement Codes
// All ads rotate. There are 3 types: square, text, and banner. Add HTML code to the array

$squareAds = array('<iframe scrolling="no" style="border: 0; width: 250px; height: 250px;" src="http://myadserver.com"></iframe>');

$textAds = array('<p><strong><a href="http://yoururl.com">YourURL</a></strong></p>', '<p><strong>Get your own site</strong> <a href="http://yoursite.com">here</a></p>');

$bannerAds = array('<iframe scrolling="no" style="border: 0; width: 468px; height: 60px;" src="http://youradserver.com"></iframe>
');
?>

Then, on the page you are serving, say, index.php to display your random links or images or text simply put:

<?php
require_once('config.php');
function getAd($arr){
    return $arr[rand(0, count($arr)-1)];
}
echo "any plain text or html" . getAd($textAds) . "any plain text or html" . getAd($bannerAds) . "any plain text or html" . getAd($squareAds) . "any plain text or html";
?>

Of course, you can create as many $xxxAds arrays and name them whatever you want, and you can fill in the arrays with whatever html or jscript to be displayed, as well as an unlimited number per array, in csv format you can also create as many new "getAd" functions with different names so that you can have multiple unique iframe ads being displayed on one page


Add image in array with full path or directory path, after refresh page image add in body tag like <body background="images/image1.jpg">

<script type="text/javascript">
function changeRandomimage() {
    var imageArray = ["images/image1.jpg","images/image2.jpg","images/image3.jpg"];
    var randomImage = Math.floor(Math.random() * imageArray.length);
    document.body.background = imageArray[randomImage];
}
changeRandomimage();
</script>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜