Is there an easier way to load random images? - javascript

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>

Related

Define image size with random image code?

At the moment I'm working with Elementor on Wordpress. What I'd like to do is have one of "modules" in Elementor filled with random images that also have each a different link to some page. I looked for a random image widget but those I found didn't provide a function to define a different link for each randomized image. So I decided to use the html widget on Elementor to use my own code. I'm not super skilled at this. So I have a code, the randomizing is working, so are the links but I don't know how to define a max. width for the images because they just fill the whole page with this code. My english isn't very good I hope someone might be able to help me and where to put something in the code to define the images size?
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var imageUrls = [
"IMAGE1“
, "IMAGE2“
, "IMAGE3“
];
var imageLinks = [
"LINK1“
, "LINK2“
, "LINK3“
];
function getImageHtmlCode() {
var dataIndex = Math.floor(Math.random() * imageUrls.length);
var img = '<a href=\"' + imageLinks[dataIndex] + '"><img src="';
img += imageUrls[dataIndex];
img += '\" alt=\"\"/></a>';
return img;
}
</script>
</head>
<script type="text/javascript">
document.write(getImageHtmlCode());
</script>
</body>

Add Links to Images in a Script

This script replaces the background of the DIV 'middle' with the images listed in the array. Currently the script works perfect but I want to be able to assign a link to each image, tried just replacing with but then the image doesn't show up nor does the link work.
<script>
var images=new Array('/images/home/imgone.jpg', '/images/home/imgtwo.jpg', '/images/home/imgthree.jpg', '/images/home/imgfour.jpg', '/images/home/imgfive.jpg');
var nextimage=0;
doSlideshow();
function doSlideshow(){
if(nextimage>=images.length){nextimage=0;}
$('.middle')
.css('background-image','url("'+images[nextimage++]+'")')
.fadeIn(500,function(){
setTimeout(doSlideshow,5000);
});
}
</script>
What I'm looking for is something like this.
<script>
var images=new Array('/images/home/imgone.jpg', '/images/home/imgtwo.jpg', '/images/home/imgthree.jpg', '/images/home/imgfour.jpg', '/images/home/imgfive.jpg'); To: var images=new Array('<img src="/images/home/imgone.jpg"', '<img src="/images/home/imgtwo.jpg"', '<img src="/images/home/imgthree.jpg"', '<img src="/images/home/imgfour.jpg"', '<img src="/images/home/imgfive.jpg"');
</script>
Although this does not fully answer your question, maybe you can get some ideas from DOM functions.
Example
<script>
// Creates Image
var image = document.createElement("img");
// Sets Image Attributes
image.src = "http://i.imgur.com/gqdqudn.png";
image.width = "30";
image.height = "30";
// Adds Image to Body
document.body.appendChild(image);
</script>
This appends an image to the body. If you would like to add it to a specific ID, you could do the following (assuming your div id is "destination").
Example
<!DOCTYPE html>
<html>
<body>
<div id="destination">
<!-- Destination Div -->
</div>
<script>
// Creates Image
var image = document.createElement("img");
// Sets Image Attributes
image.src = "http://i.imgur.com/gqdqudn.png";
image.width = "30";
image.height = "30";
// Adds Image to Body
document.getElementById("destination").appendChild(image);
</script>
</body>
</html>
Good luck!

Javascript random image generator in css-based page

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)

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>

Background Image Rotator

I need some suggestions and ideas to improve a background image rotator.
The script as of now is very basic but I'm looking to change 2 thing.
I want the images to fade into each other.
I need to be able to preload the images so it doesn't have the delay when loading them when they first display.
Thoughts?
<script type="text/javascript">
var images = ['bg1.png', 'bg2.png', 'bg3.png'];
var curImage = 0;
function switchImage()
{
curImage = (curImage + 1) % images.length
document.body.style.backgroundImage = 'url(images/' + images[curImage] + ')'
}
window.setInterval(switchImage, 5000);
</script>
Example: http://www.nickersonweb.com/demo/PMS/index.html
For fading, try fadeOut() and fadeIn() with jQuery. (Demo and documentation here: http://api.jquery.com/fadeOut/, http://api.jquery.com/fadeIn/)
For preloading, trying making an invisible image somewhere on the page, like this:
<img src='bg1.png' width="0" height="0">
Another way to preload the images is using javascript to create an image object. Here's the code I used for something similiar.
var imgnum=0;
var imgsrcs=new Array("imgs/img1.jpg","imgs/img2.jpg")
var fimgs=new Array();
var imgid="imgid";
function timedCount()
{
$("#"+imgid).fadeTo(1000,0,function(){newimage();
});
setTimeout(timedCount,5000);
}
function newimage()
{
imgnum=(imgnum+1)%imgsrcs.length;
document.getElementById(imgid).src=fimgs[imgnum].src;
$("#"+imgid).fadeTo(1000,1);
}
function initializeslideshow()
{
var i;
for(i=0;i<imgsrcs.length;i++)
{
fimgs[i]=new Image(270,270)
fimgs[i].src=imgsrcs[i];
}
}
initializeslideshow();
setTimeout(timedCount,5000);
You'll need to link to jQuery (and jQuery UI, I think) to use the code above, like this, for instance:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/jquery-ui.min.js"></script>

Categories