Random image appear when website is loaded - javascript

I have 2 pictures for my website, and i want it to load one of them whem the website loads.
I have tried using some javascript. But i am quite new to all this.
This is how i am think i want to make it.
<div class="image">
Show one of 2 images here.
</div>
<script>
var r = Math.floor(Math.random() * 100) + 1;
if(r < 51) {
SHOW IMAGE 1
}
else {
SHOWIMAGE 2
}
</sccript>
So i was hoping someone could teach me how to actually turn this into functional code.
Thanks.

You can set the src attribute of an image directly using javascript, then use Math.random like you expected to pick between different image urls.
With an image tag with id 'random_image':
// images from wikipedia featured images/articles 2015-03-03
var img = document.getElementById('random_image');
if (Math.random() > .5) {
img.src = 'http://upload.wikimedia.org/wikipedia/en/thumb/4/45/Bradford1911.jpg/266px-Bradford1911.jpg';
} else {
img.src = 'http://upload.wikimedia.org/wikipedia/commons/thumb/a/ae/Pitta_sordida_-_Sri_Phang_Nga.jpg/720px-Pitta_sordida_-_Sri_Phang_Nga.jpg';
}
Here is a jsfiddle example: http://jsfiddle.net/8zd5509u/

1.way:
var _img = document.getElementById('id1');
var newImg = new Image;
newImg.onload = function() {
_img.src = this.src;
}
newImg.src = 'http://www.something.blabla.....';
another:
function preload(images) {
if (document.images) {
var i = 0;
var imageArray = new Array();
imageArray = images.split(',');
var imageObj = new Image();
for(i=0; i<=imageArray.length-1; i++) {
//document.write('<img src="' + imageArray[i] + '" />');// Write to page (uncomment to check images)
imageObj.src=imageArray[i];
}
}
}
Then in the of each web page, add the following code after you've called the main JavaScript file:
<script type="text/javascript">
preload('image1.jpg,image2.jpg,image3.jpg');
</script>

Related

Preloading Images in JavaScript (Need an Alert When Completed)

I have the following code below, which successfully preloads images into the browser cache when the PreloadAllImages function is called. Does anyone know how to send a simple alert, e.g. "All images have been preloaded into the browser cache." when the last image (or all images) is loaded. I have 300 images, so setTimeOut won't work for latency/download lag reasons. I've tried callbacks, placing alert commands in different places, etc... but have not been successful.
This code is based on JavaScript Only Method #1 found here. https://perishablepress.com/3-ways-preload-images-css-javascript-ajax/
function PreLoadAllImages() {
var images = new Array();
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image();
images[i].src = preload.arguments[i];
}
}
preload('Images/Image1.jpg', 'Images/Image2.jpg', ... , 'Images/Image300.jpg');
}
With some help, this is how the problem was solved in case anyone else needs it. Loaded images into an invisible div on the html page, then ran script to ensure everything was loaded. A button calls PreLoadAllImages() and then CheckImages().
var imagefiles = [
"Images/Image1.jpg",
"Images/Image2.jpg",
.....
"Images/Image300.jpg"];
function PreLoadAllImages () {
imagefiles.forEach(function(image){
var img = document.createElement('img');
img.src = image;
document.body.appendChild(img);});
$('img').hide();
}
var all_loaded;
function CheckImages() {
$('img').each(function(){ // selecting all image element on the page
var img = new Image($(this)); // creating image element
img.src = $(this).attr('src'); // pass src to image object
if(img.complete==false) {
all_loaded=false;
return false;
}
all_loaded=true;
return true;});
}
function CheckLoadingImages() {
var result;
var Checking=setInterval(function(){
result=CheckImages();
if(all_loaded==true) {
clearInterval(Checking);
MsgAfterLoading();
}
}, 2000);
}
function MsgAfterLoading() {
alert('All Images Loaded');
}
You could check if i is equals to the length of the array, so it will look like:
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
//the code
if (i == preload.arguments.length){
alert("Last image loaded");
}
//the code
}
Let me know if you have any questions.
Could you try looping through all the image elements and check the naturalWidth property, if they are all greater than 0 and its the last image then alert.
This link: Preloading Images in JavaScript (Need an Alert When Completed) should help
A promise might resolve your problem.
https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Promise
var myPromise = new Promise( function(resolve, reject) {
// preload code
resolve(true);
};
myPromise.then(function() {
// your alert
};
You can use the onload event.
function PreLoadAllImages() {
var images = new Array();
var numberofimages = 0, loadedimages = 0;
function preload() {
numberofimages = preload.arguments.length;
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image();
images[i].src = preload.arguments[i];
images[i].onload = () => {
loadedimages++;
if(loadedimages == numberofimages){
alert("All images are loaded");
}
}
}
}
preload('Images/Image1.jpg', 'Images/Image2.jpg', ... , 'Images/Image300.jpg');
}

Preloader for loading images

I am currently working on SVG SMIL animation in which I am using some .png and .gif files for easing my animation in IE. For this animation I am trying to get Preloader before animation and its other contents get loaded.
Problem is I am not getting that Preloader working properly. My .html page is getting loaded first and then preloader is starting... In Preloader also, I have used several preloaders available on the web. But they are not helpful for me.
Script and .html files loading time can be counted by domContentLoaded but for images. I dont know how to do that. If someone can suggest me a way that would be great.
here is code of preloader.js, I found on web:
$(document).ready(function () {
"use strict"
//indexOf support for IE8 and below.
if (!Array.prototype.indexOf){
Array.prototype.indexOf = function(elt /*, from*/){
var len = this.length >>> 0;
var from = Number(arguments[1]) || 0;
from = (from < 0)
? Math.ceil(from)
: Math.floor(from);
if (from < 0)
from += len;
for (; from < len; from++){
if (from in this &&
this[from] === elt)
return from;
}
return -1;
};
}
//bgImg for holding background images in the page & img array for images present in the document(<img src="">).
var bgImg = [], img = [], count=0, percentage = 0;
//Creating loader holder.
$('<div id="loaderMask"><span>0%</span></div>').css({
position:"fixed",
top:0,
bottom:0,
left:0,
right:0,
background:'#fff'
}).appendTo('body');
//Using jQuery filter method we parse all elemnts in the page and adds background image url & images src into respective arrays.
$('*').filter(function() {
var val = $(this).css('background-image').replace(/url\(/g,'').replace(/\)/,'').replace(/"/g,'');
var imgVal = $(this).not('image').attr('xlink:href');
//Getting urls of background images.
if(val !== 'none' && !/linear-gradient/g.test(val) && bgImg.indexOf(val) === -1){
bgImg.push(val)
}
//Getting src of images in the document.
if(imgVal !== undefined && img.indexOf(imgVal) === -1){
img.push(imgVal)
}
});
//Merging both bg image array & img src array
var imgArray = bgImg.concat(img);
console.log(imgArray.length);
//Adding events for all the images in the array.
$.each(imgArray, function(i,val){
//Attaching load event
$("<image />").attr("xlink:href", val).bind("load", function () {
console.log('val'+val);
completeImageLoading();
});
//Attaching error event
$("<image />").attr("xlink:href", val).bind("error", function () {
imgError(this);
});
})
//After each successful image load we will create percentage.
function completeImageLoading(){
count++;
percentage = Math.floor(count / imgArray.length * 100);
console.log('percentage:'+percentage);
$('#loaderMask').html('<span>'+percentage + '%'+'</span>');
//When percentage is 100 we will remove loader and display page.
if(percentage == 100){
$('#loaderMask').html('<span>100%</span>')
$('#loaderMask').fadeOut(function(){
$('#loaderMask').remove()
})
}
}
//Error handling - When image fails to load we will remove the mask & shows the page.
function imgError (arg) {
$('#loaderMask').html("Image failed to load.. Loader quitting..").delay(3000).fadeOut(1000, function(){
$('#loaderMask').remove();
})
}
});
A little trick I do to ensure my or external data or images are loaded before I start executing my js code is, I create a div with display:none and fill it with all the tags that I need loaded.
<body>
<span id="loadingText">Loading...</span>
<div style="display:none">
<img src="pathtoimage1">
<img src="pathtoimage2">
<img src="pathtoimage3">
</div>
<script>
window.onload = function(){
//This gets called when all the items in that div has been loaded and cached.
document.getElementById("loadingText").style.display = "none";
}
</script>
</body>
I use this for preloading images for animations.
you can add and remove how many you load as needed.
<script language="javascript">function preloader() {
if (document.images) {
var img1 = new Image();
var img2 = new Image();
var img3 = new Image();
var img4 = new Image();
var img5 = new Image();
var img6 = new Image();
var img7 = new Image();
var img8 = new Image();
var img9 = new Image();
img1.src = "image link here";
img2.src = "image link here";
img3.src = "image link here";
img4.src = "image link here";
img5.src = "image link here";
img6.src = "image link here";
img7.src = "image link here";
img8.src = "image link here";
img9.src = "image link here";
}
}
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function() {
if (oldonload) {
oldonload();
}
func();
}
}
}
addLoadEvent(preloader);</script>

Use javascript to write html around loop

I'm using the javascript from this older script: JavaScript: how to load all images in a folder?
However, I want to use the same javascript file to write some html code before the loop and some after the loop, all using this same javascript file.
Just putting a document.write before and after it in the javascript doesn't work.
var bCheckEnabled = true;
var bFinishCheck = false;
var img;
var imgArray = new Array();
var i = 0;
var myInterval = setInterval(loadImage, 1);
function loadImage() {
if (bFinishCheck) {
clearInterval(myInterval);
document.write('Loaded ' + i + ' image(s)');
return;
}
if (bCheckEnabled) {
bCheckEnabled = false;
img = new Image();
img.onload = fExists;
img.onerror = fDoesntExist;
img.src = 'assets/' + i + '.png';
document.write('<img src="assets/' + i + '.png" width="1016" height="813" alt="Kar" />');
}
}
function fExists() {
imgArray.push(img);
i++;
bCheckEnabled = true;
}
function fDoesntExist() {
bFinishCheck = true;
}
You may be using this example code incorrectly. Its intent appears to be to pre-load the image files in the background, not display them to the user in the HTML (yet). This is to improve apparent download speed of your page.
In short, this code doesn't actually render the image into the DOM; and that is intentional behavior.

Mouseover even in javascript wont output

Oh the splash screen of my new site I wish to have a mouseover event which will change the colour of my logo every time the mouse is moved. Below I have listed the code I have so far, but I cannot get it to display my image.
var images = new Array()
images[0] = 'img/CMbl.png'
images[1] = 'img/CMo.png'
images[2] = 'img/CMg.png'
images[3] = 'img/CMp.png'
images[4] = 'img/CMblu.png'
var p = images.length;
logo = document.getElementById( 'logo' ),
console = document.getElementById( 'console' );
logo.addEventListener('mousemove', changeImage);
function changeImage() {
var rand = Math.round(Math.random()*(p-1));
var image = p[ rand ];
if ( image == logo.src ) {
changeImage();
return false;
}
logo.src = console.innerText = image;
function showImage(){
document.write('<img src="+image[rand]">');
}
}
and my output in html should be (Inside the class 'logo')
<script language="javascript">
showImage()
</script>
I cannot see why it's not working. I am using a similar code to change image on refresh, which still uses math.random() and an array to call the images.
This is the way this should look:
document.write('<img src="' + image[rand] + '">');
(your script is full of mistakes from what I can see. I'll make a quick, working one for you as an example.)
Here is a working example(I think this is what you're going for) Jsfiddle example
As you can see, it comes out to a terrible looking effect, I wouldn't suggest using it.
I've made a JSfiddle which cleans up some of the code, and makes use of jQuery.
http://jsfiddle.net/jackcannon/2EXs5/
var images = [
'http://colorvisiontesting.com/plate%20with%205.jpg',
'http://regentsparkcollege.org.uk/wp-content/uploads/2012/09/test.jpg',
'http://nyquil.org/uploads/IndianHeadTestPattern16x9.png',
'http://25.media.tumblr.com/tumblr_m9p3n1vJmZ1rexr16o1_400.jpg',
'http://www.themoralofthestoryis.com/wp-content/uploads/2013/01/test.gif'
];
$('#logo').mouseover( changeImage );
function changeImage() {
var rand = Math.floor(Math.random() * images.length);
var image = images[ rand ];
if ( image == $('#logo').attr('src') ) {
changeImage();
return false;
}
$('#logo').attr('src', image);
};

Generic Javascript Image Swap

I'm building a navigation bar where the images should be swapped out on mouseover; normally I use CSS for this but this time I'm trying to figure out javascript. This is what I have right now:
HTML:
<li class="bio"><img src="images/nav/bio.jpg" name="bio" /></li>
Javascript:
if (document.images) {
var bio_up = new Image();
bio_up.src = "images/nav/bio.jpg";
var bio_over = new Image();
bio_over.src = "images/nav/bio-ov.jpg";
}
function over_bio() {
if (document.images) {
document["bio"].src = bio_over.src
}
}
function up_bio() {
if (document.images) {
document["bio"].src = bio_up.src
}
}
However, all of the images have names of the form "xyz.jpg" and "xyz-ov.jpg", so I would prefer to just have a generic function that works for every image in the navbar, rather than a separate function for each image.
A quick-fire solution which should be robust enough provided all your images are of the same type:
$("li.bio a").hover(function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace(".jpg", "") + "-ov.jpg";
}, function() {
var $img = $(this).find("img");
$img[0].src = $img[0].src.replace("-ov.jpg", "") + ".jpg";
});
This should work will all image formats as long as the extension is between 2 and 4 characters long IE. png, jpeg, jpg, gif etc.
var images = document.getElementById('navbar').getElementsByTagName('img'), i;
for(i = 0; i < images.length; i++){
images[i].onmouseover = function(){
this.src = this.src.replace(/^(.*)(\.\w{2,4})$/, '$1'+'-ov'+'$2');
}
images[i].onmouseout = function(){
this.src = this.src.replace(/^(.*)-ov(\.\w{2,4})$/, '$1'+'$2');
}
}
Here's an idea in plain javascript (no jQuery):
function onMouseOverSwap(e) {
e.src = e.src.replace(/\.jpg$/", "-ov.jpg"); // add -ov onto end
}
function onMouseOutSwap(e) {
e.src = e.src.replace(/(-ov)+\.jpg$/, ".jpg"); // remove -ov
}

Categories

Resources