Javascript random image generator in css-based page - javascript

as the title says I'm trying to figure out how to call this javascript function in my webpage. It's for my business, and the template is just a basic, free one. I'm sure for someone more experienced than me it's probably just a simple matter of formatting it correctly. Here's what I'm working with.
Code that goes in the HEAD portion of the webpage:
var theImages = new Array()
theImages[0] = 'splash1.jpg'
theImages[1] = 'splash2.jpg'
theImages[2] = 'splash3.jpg'
theImages[3] = 'splash4.jpg'
theImages[4] = 'splash5.jpg'
theImages[5] = 'splash6.jpg'
var j = 0
var p = theImages.length;
var preBuffer = new Array()
for (i = 0; i < p; i++){
preBuffer[i] = new Image()
preBuffer[i].src = theImages[i]
}
var whichImage = Math.round(Math.random()*(p-1));
function showImage(){
document.write('<img src="'+theImages[whichImage]+'">');
}
</script>
Now to call the function I use:
<SCRIPT LANGUAGE="JavaScript">
showImage();
</script>
Here's the page in which I'm trying to implement it:
http://coloradopp.com/index4.html
Instead of just displaying an image, I would like to call that function. Splash 1-6 are all the same size as the original image.
Here's the code snippet:
<div id="splash">
<img class="pic" src="images/splash1.jpg" width="870" height="374" alt="" />
</div>
As you can tell the page calls on a style sheet (style.css) for all the formatting.
Can anyone offer any tips on how to make this work? From what I've gathered, one cannot implement javascript into css sheets. Thanks in advance.

Do something like this:
showImage() {
var theImages = [ 'splash1.jpg', 'splash2.jpg', 'splash3.jpg', 'splash4.jpg', 'splash4.jpg' ];
var img = theImages[Math.round(Math.random() * (theImages.length - 1))];
document.getElementById('splash').innerHTML = '<img src="' + img + '">');
}

First move your javascript code inside the function something like:
function showImage(){ ...your code goes here...}
And then you can initiate the function on page load like this:
<body onload="showImage()">

You can set the images dynamically as background-image and place something like this
<script>
document.write('<style>#splash{ background-image:url(\'images/splash'+Math.round(Math.random()*5+1)+'.jpg\');}</style>');
</script>
at the head of your page. With this solution you have to set fix dimensions for your div tag (870x374)

Related

Image array for javascript slideshow not appearing

I'm making a slideshow in javascript for a class assignment and I have the slideshow working but it's not displaying the images. I can see that the image icon changes but the actual image is not showing.
<script type="text/javascript">
//put images in array
var pics = new Array();
pics[0] = new Image();
pics[0].src = "images/forest.jpg";
pics[1] = new Image();
pics[1].src = "images/mountains.jpg";
pics[2] = new Image();
pics[2].src = "images/nature.jpg";
pics[3] = new Image();
pics[3].src = "images/snowtops.jpg";
var index = 0; //start point
var piclength = pics.length - 1;
function slideshow() {
document.slide.src = pics[index];
if (index < piclength) {
index++;
}
else {
index = 0;
}
}
function slide() {
setInterval(slideshow, 3000);
}
</script>
<body onload="slide()">
<h1>Nature Photography</h1>
<main>
<section>
<p>I am an enthusiastic about nature photography. Here is a slideshow of my
works.</p>
<aside> <img id="myImage" src="images/forest.jpg" name="slide" width="95%">
</aside>
First, I would put the script tag after your HTML. This will allow you to cache DOM elements without waiting for the "DOMContentLoaded" event or the "load" (window) event to be fired.
Second, you should cache the "myImage" element. Something like const slider = document.getElementById('myImage').
Third, check your console. Maybe your image URLs are wrong? And make sure your HTML is valid. From what you posted, you are missing a lot of things (doctype, html/head tags, you didn't close body tag and similar)

ID tag created with var for img Jscript html

Could anybody be so kind as to direct myself and the many other NOVICE LEARNERS who come here seeking Appreciative suggestions for a solution such as this problem please?
I have managed to create an array for the src and the image but i cannot find a way to append a ID array to the ID tag of the IMG that is HTML. i.e img id="foo" src = "bar" ect ect. i wish to have a n array for the ID .
I wish to start coding dry , and i have been watching many vids and tutorials and have managed to get this far...
<html>
<body>
<var x=0; x<10; x++1>
<img id="0" src="cicons1.png" style="position:absolute;">
<script>
var i=0
function setup() {
document.getElementById([i]).style = ("position:absolute; left:"+[i*100+100]+"px;" )
document.getElementById([i]).src="Cicons"+[i]+".png";
console.log([i])
}
for (var i=0; i<10; i=i+1) { setup();
}
</script>
</body>
</html>
But i wish to have an array for the ID also so i donnot have to repeat the image tag
over and over again. as i am dealing with over 60+ icons and images and text captions. so it would be ideal to have a DRY method, And i have failed very badly to provide a solution myself, So now i must turn to the experts..
So i thank you in advance if you have a solution..
https://ibb.co/ifGcKk
Please, be aware there are really a lot of ways to do such a task, here is just an example:
<html>
<body>
<div id="iconContainer"></div>
<div id="icoSelected" style="position: absolute; top: 120px;">Selected: -none-</div>
<script>
function showSelected() {
document.getElementById('icoSelected').innerHTML = this.src;
}
function setup(cnt, id) {
var imgEl = document.createElement('img');
var icoName = "Cicons"+id+".png";
imgEl.id = 'icon-'+id;
imgEl.style.position = 'absolute';
imgEl.style.left = (id-1)*100+20+'px';
imgEl.style.width = '80px';
imgEl.style.height = '80px';
imgEl.src = icoName;
imgEl.addEventListener('click', showSelected);
cnt.appendChild(imgEl);
}
var cont = document.getElementById('iconContainer');
for (var i=0, nIcons=10; i<nIcons; i++) {
setup(cont, i+1);
}
</script>
</body>
</html>

Is there an easier way to load random images?

I don't think I explained this properly, but I ended up answering my own question, basically I was looking remove the head code because it made the document look ugly and was very tedious everytime when it came to scrolling, I put the head javascript code into it's file and removed the code from index head section and it seems to be working just fine.
Thanks all for the help!
/close
/answered
Can anybody point towards an easier method to load random images on my index.html page?
This is the current method I'm using
In the head section:
// It currently goes to css/images/images/410.png, I have just put six here so it isn't long and annoying
<script type="text/javascript">
var imageURLs = [
"css/images/avatars/1.png"
, "css/images/avatars/2.jpg"
, "css/images/avatars/3.png"
, "css/images/avatars/4.png"
, "css/images/avatars/5.png"
, "css/images/avatars/6.png"
];
function getImageTag() {
var img = '<img src=\"';
var randomIndex = Math.floor(Math.random() * imageURLs.length);
img += imageURLs[randomIndex];
img += '\" alt=\"Oh no, the image is broken!\"/>';
return img;
}
</script>
In the body section:
<!-- RANDOM IMAGE 1 -->
<script type="text/javascript">
document.write(getImageTag());
</script>
<!-- RANDOM IMAGE 2 -->
<script type="text/javascript">
document.write(getImageTag());
</script>
I currently have 410 images altogether so you can image how annoying it is within the head section code
If your images are all named like that, this should work:
<script type="text/javascript">
var imagesCount = 410;
function getImageTag() {
var img = '<img src=\"css/images/avatars/';
var randomIndex = 1+Math.floor(Math.random() * imagesCount );
img += randomIndex;
img += '.png\" alt=\"Oh no, the image is broken!\"/>';
return img;
}
</script>

How can i return img.src by clicking on an image with javascript?

I am trying to create a function with javascript where a user upon clicking on an image can retrieve that images src as a URL. I am very new to javascript and my attempts so far at creating a function activated by "onclick" of an image are:
var showsrc = function(imageurl)
var img = new Image();
img.src = imageurl
return img.src
to call the results i have been trying to insert the image.src into my html using
document.getElementById("x").innerHTML=imageurl;
Im having very little success. Any help would be greatly appreciated. Thank you.
I tested this in IE9 and Chrome 17. Add an onclick handler to the body (or nearest container for all your images) and then monitor if the clicked element is an image. If so show the url.
http://jsfiddle.net/JbHdP/
var body = document.getElementsByTagName('body')[0];
body.onclick = function(e) {
if (e.srcElement.tagName == 'IMG') alert(e.srcElement.src);
};​
I think you want something like this: http://jsfiddle.net/dLAkL/
See code here:
HTML:
<div id="urldiv">KEINE URL</div>
<div>
<img src="http://www.scstattegg.at/images/netz-auge.jpg" onclick="picurl(this);">
<img src="http://www.pictokon.net/bilder/2007-06-g/sonnenhut-bestimmung-pflege-bilder.jpg.jpg" onclick="picurl(this);">
</div>​
JAVASCRIPT
picurl = function(imgtag) {
document.getElementById("urldiv").innerHTML = imgtag.getAttribute("src");
}​
Image tags do not have an 'innerHTML', since they're singleton tags - they cannot have any children. If your x id is the image tag itself, then:
alert(document.getElementById('x').src);
would spit out the src of the image.
Here's a naïve solution with just javascript (probably not cross-browser compatible):
<!doctype html>
<html>
<head>
<script>
function init() {
var images = document.getElementsByTagName('img');
for(var i = 0, len = images.length; i < len; i++) {
images[i].addEventListener('click', showImageSrc);
}
}
function showImageSrc(e) {
alert(e.target.src);
}
</script>
</head>
<body onload="init()">
<img src="http://placekitten.com/300/300">
</body>
</html>

Javascript will not load the pictures

I want to load these banner.png files to the screen but all it prints out is the actual text from the banner array?
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
return banner[randNum];
}
any thoughts? I think I need to some how add a src but I am not sure how.
Might be too obvious, but...
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
return '<img src="' + banner[randNum] + '" />';
}
Demo: http://jsfiddle.net/AlienWebguy/u7yfq/
My pure javascript DOM manipulation is a little fuzzy (usually use jquery) but something like this should do the trick:
<div id="images"></div>
<script type="text/javascript">
function randImg(){
var banner = new Array();
banner[0] = 'banner1.png';
banner[1] = 'banner2.png';
banner[2] = 'banner3.png';
maxImg = banner.length;
randNum = Math.floor(Math.random()*maxImg);
var container = document.getElementById('images');
var img = document.createElement('img');
img.setAttribute('src',banner[randNum]);
container.appendChild(img);
}
</script>
The instruction that loads the image should be like this.
Where imgElement is an IMG element.
imgElement.src = randImg();
If you don’t know how to get an IMG element. Give the IMG element an ID attribute and load this like this.
For an IMG element as <img id="myImage" src="" />
Then:
var imgElement = document.getElementById("myImage");
imgElement.src = randImg();
Note.- my answer gives instruction on how to change the source of an IMG element that exists in the DOM (It is recommended to do so). You should NEVER document.write() an element, Neither on demand or when page is loading. That practice has been deprecated and many browsers would delete the whole page contents if you do so.

Categories