This code works perfectly fine by itself but as soon as I embed it into a website it no longer loads an image on page load. Why? How can it be improved?
My guess is the susceptible windowon.load
. Maybe it can be substituted?
//$(document).ready(function(){choosePic;}
//alert(window.onload);
//https://stackoverflow.com/questions/2810825/javascript-event-window-onload-not-triggered;
window.onload = choosePic;
var onl oadd = window.onload;
var myPix = new Array(
"https://m.box.com/file/903146245504/https://app.box.com/s/j7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png",
"https://m.box.com/file/1055524661946/https://app.box.com/s/j7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png",
"https://m.box.com/file/896387464705/https://app.box.com/s/j7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png"
);
function choosePic() {
var randomNum = Math.floor(Math.random() * myPix.length);
document.getElementById("myPicture").src = myPix[randomNum];
('#myPicture').html(` ${myPicture} `);
('#today').html(` ${onloadd} `);
}
<button id=onloadd></button>
<button id="myrdpbtn" style="background:transparent; border:transparent;" onclick="choosePic()">RandomPicture</button>
<button id=onloadd></button><br>
<img src="https://ry3yr.github.io/OSTR/release/0mine/documents/art/empty.png" width=1000 id="myPicture"><br><br>
CodePudding user response:
This works.
<!----RandomImage--->
<button id="myrdpbtn" style="background:transparent; border:transparent;" onclick="swap()">RandomPicture</button>
<style type="text/css">
#banner {height:100%;object-fit: contain;
//padding:0;margin:0;text-align:right;
//position:relative;
//position:absolute; top: 0px; left: 1200px;
//background-position: center center;
background-size: contain;
background-repeat: no-repeat;}</style>
<script type="text/javascript">
if (document.getElementById) { window.onload = swap };
function swap() {
var numimages=8;
rndimg = new Array(
"https://m.box.com/file/903146245504/https://app.box.com/s/j7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png",
"https://m.box.com/file/905690094898/https://app.box.com/s/j7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png",
"https://cdnb.artstation.com/p/assets/images/images/055/144/127/large/ryedai1-2022-10-19-aoi-realist-no2.jpg?1666212593",
"https://other00.deviantart.net/c476/o/2021/321/8/f/subaru_and_misora_by_pasc91.png",
"https://m.box.com/file/900365515983/https://app.box.com/s/j7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png",
"https://m.box.com/file/889506897379/https://app.box.com/s/j7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png",
"https://m.box.com/file/903146245504/https://app.box.com/s/j7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png",
"https://m.box.com/file/896387464705/https://app.box.com/s/j7i88s6jb4yyk4wmiti4tol8ejoikdhl/preview/preview.png"
);
x=(Math.floor(Math.random()*numimages));
randomimage=(rndimg[x]);
document.getElementById("banner").style.backgroundImage = "url(" randomimage ")";
}</script>
</head>
<div id="banner""></div>