JS basic random image select - javascript

I've only started HTML yesterday and I'm trying to do a really basic memory game. First, there's an image of all the pieces, then a button that calls a function that hides that image and make another appear. This second image is a blank page with the spaces where the parts of the former image were. Also, there's an usemap and a function that returns if the player has clicked correctly or not. My problem is to come up with a function (and how to call it) to select a random part of the image.
function checkAnswer(a) {
if (a=='6') {
alert('Correct!')
}
else {
alert('Wrong!')
}
}
The 'a' must be a random number and follow the index of the chosen picture.
This is what I've found, but couldn't use:
<!-- Attempt of random
function random_imglink() {
var cobras=new Array()
cobras[1]="<img src ="..\images\Cobra1.jpg">"
cobras[2]="..\images\Cobra2.jpg"
cobras[3]="..\images\cobra3.jpg"
cobras[4]="..\images\cobra4.jpg"
cobras[5]="..\images\cobra5.jpg"
cobras[6]="..\images\cobra6.jpg"
cobras[7]="..\images\cobra7.jpg"
cobras[8]="..\images\cobra8.jpg"
cobras[9]="..\images\cobra9.jpg"
cobras[10]="..\images\cobra10.jpg"
cobras[11]="..\images\cobra11.jpg"
cobras[12]="..\images\cobra12.jpg"
cobras[13]="..\images\cobra13.jpg"
cobras[14]="..\images\cobra14.jpg"
cobras[15]="..\images\cobra15.jpg"
var ry=Math.floor(Math.random()*cobras.length)
if (ry=='0') {
ry = '1'
}
document.write('<img src="'+myimages[ry]+'" border=0>')
}
-->
<!-- Attempt of random
<script>
var imgArray = new Array();
imgArray[0] = new Image();
imgArray[0].src = '..\images\Cobra1.jpg';
imgArray[1] = new Image();
imgArray[1].src = '..\images\Cobra2.jpg';
imgArray[2] = new Image();
imgArray[2].src = '..\images\cobra3.jpg';
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src)
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
</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');
}

Swapping the position of two images with JavaScript

So i am trying to make it so if you click on the button it will switch the images placement. However it doesnt actually switch the placement but instead just changes the src of each image ID. It works when you click the button once, but after that the images no longer switch. This is my code
function swapImages(){
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src = '/jmurphy9/111/images/earthrise.jpg') {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src = '/jmurphy9/111/images/earth.jpg') {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
function init(){
var button1 = document.getElementById("btn1")
button1.onclick = swapImages;
}
window.onload = init;
The problem is the src property will have the absolute path to the image, not relative one as you are checking
One possible solution is to use .indexOf() as given below
function swapImages() {
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src.indexOf('/jmurphy9/111/images/earthrise.jpg')>-1) {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src.indexOf( '/jmurphy9/111/images/earth.jpg')>-1) {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
Or you can use .getAttribute()
if (image1.getAttribute('src') == '/jmurphy9/111/images/earthrise.jpg') {
}
But since you want to swap, you can just do
function swapImages() {
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
var src = image1.src;
image1.src = image2.src;
image2.src = src;
}
Demo: Fiddle
Note: In your if condition you are using assignment(=) operator instead of comparison operator(==), so image1.src = '/jmurphy9/111/images/earthrise.jpg' in the if should be image1.src == '/jmurphy9/111/images/earthrise.jpg'
Looks like your equality operator is missing an extra "=" on your if's e.g. if(image1.src == '/jmurphy9/111/images/earthrise.jpg') so when it tries to evaluate the expression it never goes in so it changes the first time 'cause it goes to the else and from there on it just keeps going to the else so nothing happens.
function swapImages(){
var image1 = document.getElementById("image1")
var image2 = document.getElementById("image2")
if (image1.src == '/jmurphy9/111/images/earthrise.jpg') {
image1.src = '/jmurphy9/111/images/earth.jpg';
} else {
image1.src = '/jmurphy9/111/images/earthrise.jpg';
}
if (image2.src == '/jmurphy9/111/images/earth.jpg') {
image2.src = '/jmurphy9/111/images/earthrise.jpg';
} else {
image2.src = '/jmurphy9/111/images/earth.jpg';
}
}
function init(){
var button1 = document.getElementById("btn1")
button1.onclick = swapImages;
}
window.onload = init;
The accepted answer, like yours, swaps the src attribute of the images.
Another method is to actually swap the img nodes themselves, which may be preferable if the images matter severally- eg., need special event handling or css considerations that depend on the actual image.
function swapNodes(a, b){
var p= b.parentNode, sib= b.nextSibling;
if(sib=== a) sib= sib.nextSibling;
a.parentNode.replaceChild(b, a);
return sib? p.insertBefore(a, sib): p.appendChild(a);
}
note that you can always swap img nodes, or any two like nodes, but there are some nodes that cannot be swapped, because the container node of one will not accept the other as a child.
You can swap them if they make valid html.

Random image appear when website is loaded

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>

JavaScript slideshow stuck on first photo

I am a Javascript beginner trying to make a simple slideshow using Javascript. From the work I've done, I'm able to produce only one of the five images. The console says nothing is wrong and I am at a loss as to why the other pictures won't show.
<script>
var images = new Array();
images[0] = new Image();
images[0].src = "burger1.jpg";
images[1] = new Image();
images[1].src = "burger2.jpg";
images[2] = new Image();
images[2].src = "burger3.jpg";
images[3] = new Image();
images[3].src = "burger4.jpg";
images[4] = new Image();
images[4].src = "burger5.jpg";
var slide = 0;
function next(){
if (!document.images) {
return document.getElementById('slideshow').src = images[slide].src
}
if(slide < 5){
slide++;
} else{
slide = 0;
}
setTimeout("next()",3000);
}
next();
</script>
</head>
<body>
<img src="burger1.jpg" id="slideshow" width=100 height=100 />
P.S I do not know jquery.
if (!document.images) {
return document.getElementById('slideshow').src = images[slide].src
}
here !document.images is [object HTMLCollection] and you are checking ! of this use only :
if(slide < 5){
slide++;
} else{
slide = 0;
}
setTimeout(next,3000);
document.getElementById('slideshow').src = images[slide].src
Remove
if (!document.images) {
return document.getElementById('slideshow').src = images[slide].src
}
Add
document.getElementById('slideshow').src = images[slide].src
After setTimeout
There's more to fix in your code so I'll try to show you a better approach then just a quicky:
jsBin demo
var slideshow = document.getElementById('slideshow'), // Cache your element!
images = [ // Create an array of images paths
"burger1.jpg",
"burger2.jpg",
"burger3.jpg"
],
slide = 0,
tot = images.length; // count the total of images
for(var i=0; i<tot; i++){ // preload images (so we don't have to wait for them)
var img = new Image();
img.src = images[i];
}
function next() {
slideshow.src = images[slide++ % tot]; // Modulo operator to loop the counter
setTimeout(next, 3000); // Don't wrap `next` in String
}
next();

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>

Categories

Resources