JS onclick Event Handler - Not Responding - javascript

What I'm trying to achieve: clicking on any image should either reveal a clear image if image is blurred or blur the image if image is clear
What's happening: clicking on blurred image clears the image, but clicking on it again does nothing. so, clicking on a clear image does not blur it (as it should).
Here's my code:
<script>
window.onload = init;
function init(e) {
var img = document.getElementsByTagName("img");
//var img = document.getElementById('pics');
img[0].onclick = unblur; // <- why not just img.onclick = unblur ??
img[1].onclick = unblur;
img[2].onclick = unblur;
console.log(img);
/*
var imageId = e.target.id; //zero
var img = document.getElementById(imageId);
*/
//img.onclick = unblur;
}
function unblur(e) {
var imageId = e.target.id; //zero
var img = document.getElementById(imageId);
var imageSource = img.src; //zeroblur.jpg
var clearImg = imageSource.substring(0, imageSource.length - 8);
var unblurredImg = imageId.concat('.jpg'); // zero.jpg
var blurredImg = imageId.concat('blur.jpg'); // zeroblur.jpg
console.log(imageSource);
console.log(img.src);
//console.log(imageSource);
if (img.src == unblurredImg) {
img.src = blurredImg;
} else {
img.src = unblurredImg; // image is clear, so hide the pic
}
/*
if (img.src == blurredImg) {
img.src = unblurredImg;
}
} */
//}
}
/*
//if (!(imageId instanceof img)) {
if (imageId !== "pics") {
if (img.src == blurredImg) {
img.src = unblurredImg;
} else if (img.src == unblurredImg) {
img.src = blurredImg;
} // image is blurred, so reveal the pic
else {
console.log("hi");
}
//debugger;
}
}
*/
/*
var img = document.getElementById('zero');
img.src = "zero.jpg";
*/
</script>
</head>
<body>
<div id="pics">
<img id="zero" src="zeroblur.jpg">
<img id="one" src="oneblur.jpg">
<img id="two" src="two.jpg">
</div>
</body>
</html>
I also noticed that if I switch the conditions in the function, unblur(e), to the following...
if (img.src == unblurredImg) {
img.src = blurredImg;
} else {
img.src = unblurredImg;
}
there's no response at all if a user clicks on a blurred image, whereas before (code above) the blurred image will at least reveal the cleared image.
Why is this happening? I see no difference between the two, besides just switching the order of the conditions.

There are various mistakes in your example. Take a look at the Code Snippet for a working example of what you are trying to achieve.
As for your comment:
// <- why not just img.onclick = unblur ??
Because document.getElementsByTagName returns an array of elements. Therefore, you must iterate through the elements to apply the onclick handlers to each one.
(function(document) {
var array = document.getElementsByTagName("img");
for (var i = 0; i < array.length; i++) {
array[i].onclick = toggleBlur;
}
function toggleBlur(event) {
var img = event.target;
var oldSrc = img.src; // Save to display in the console
if (img.src.endsWith("blur.jpg")) {
img.src = img.id + ".jpg";
} else {
img.src = img.id + "blur.jpg"
}
console.log(oldSrc + " -> " + img.src + " on element.id=" + img.id);
}
})(document);
<body>
<div id="pics">
<img id="zero" src="zero.jpg">
<img id="one" src="one.jpg">
<img id="two" src="twoblur.jpg">
</div>
</body>

Related

Display a loading icon while loading image

I would like to be able to display a GIF while the image is being loaded. Is this possible with the script I am using?
From what I understand I would use something like
$('#image').load { loadingimage.hide }
Here is my code:
$.get('http://192.168.1.69:8090/VirtualRadar/AirportDataThumbnails.json?icao=' + p.Icao + '&reg=' + p.Reg , function(res) {
var error = res.status;
if (error == "404") {
$("#image").attr('src', "placeholder.jpg");
$("#image2").attr('src', "placeholder.jpg");
$("#imageurl").attr('href', "//airport-data.com");
} else {
var imgUrl = res.data[0].image;
var imgHref = res.data[0].link;
$("#image").attr('src', imgUrl);
$("#image2").attr('src', imgUrl);
$("#imageurl").attr('href', imgHref);
}
})
Use the Image.onload attribute or attach an event listener.. load the loading wheel image first then display that while the larger image is loading...
function loadImage(src){
return new Promise(done=>{
var i = new Image();
i.onload = ()=>done(i);
i.src = src;
});
}
const loadImgSrc = "https://media.giphy.com/media/3oEjI6SIIHBdRxXI40/giphy.gif";
const bigImgSrc = "https://www.gannett-cdn.com/-mm-/4252e7af1a3888197136b717f5f93523f21f8eb2/r=x1683&c=3200x1680/local/-/media/USATODAY/onpolitics/2012/10/03/bigbird-16_9.jpg";
loadImage(loadImgSrc).then(img=>{
img.style.maxWidth = "100%";
document.getElementById('myImg').appendChild(img);
loadImage(bigImgSrc).then(img=>{
img.style.maxWidth = "100%";
document.getElementById('myImg').innerHTML = '';
document.getElementById('myImg').appendChild(img);
});
})
<div id=myImg></div>

Create one image in javascript

I have the following code to create an image with JavaScipt, the image appear on a button click. The problem is when the image is created and i click again the button another one appear, and i don't want that.
How i can solve that?
var img = new Image();
var div = document.getElementById('Table');
img.onload = function() {
div.appendChild(img);
};
img.src = 'Images/Email.png';
You could use a flag, which indicate when the image has been created, loaded and added to your DOM:
var div = document.getElementById('Table');
var hasImage = false; // flag
var button = document.getElementById('button');
button.addEventListener('click', function(event){
createImage();
});
var createImage = function(){
if(!hasImage) {
var img = new Image();
img.src = 'http://pipsum.com/435x310.jpg';
img.onload = function() {
div.appendChild(img);
hasImage = true;
};
}else{
console.log('image is already present');
}
};
<button id="button" type="button">Click Me!</button>
<div id="Table"></div >
Check if the image is already added to the DOM. If not, do so. If already added, only update the source.
It could be something like this:
var img = new Image();
var div = document.getElementById('Table');
var appended = false;
function appendImage() {
appended = true;
div.appendChild(img);
img.removeEventListener('load', appendImage);
}
function onClick() {
if (!appended) {
img.addEventListener('load', appendImage);
}
img.src = 'Images/Email.png';
}

Trying to change an image using an array in JavaScript

<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
index=(0)
var traffic = ["Red","Rambo","Green","Yellow"]
function changeImage() {
var image = document.getElementById('Light');
if traffic[index] === "Red" {
image.src = "Rambo.jpg";
index= (index+1)
} else if traffic[index] === "Rambo" {
image.src = "Green.jpg";
index= (index+1)
} else if traffic[index] === "Green" {
image.src = "Yellow.jpg";
index= (index+1)
} else {
image.src = "Red.jpg";
index=0
}
}
</script>
</html>
</body>
this is my code I don't understand why when i click the button the image doesn't change the images are all .jpg files are all contained inside the same folders and all are the same size any ideas why is will not change the image i'm currently guessing it's something to do with the === or the fact i'm using words instead of numbers for them
Lots of things going wrong here:
Parenthese around the if statements
Closing body tag after closing html tag
document.getElementById does not get the same id as the img id
So, this will work, but perhaps checking the javascript and HTML syntax first might be a good start:
<!DOCTYPE html>
<html>
<body>
<img id="myImage" src="Red.jpg" width="209" height="241">
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
<script>
var index = 0;
var traffic = ["Red","Rambo","Green","Yellow"];
var image = document.getElementById('myImage');
function changeImage() {
if (traffic[index] === "Red") {
image.src = "Rambo.jpg";
index++;
} else if (traffic[index] === "Rambo") {
image.src = "Green.jpg";
index++;
} else if (traffic[index] === "Green") {
image.src = "Yellow.jpg";
index++;
} else {
image.src = "Red.jpg";
index = 0;
}
}
</script>
</body>
</html>
There are few little mistakes in your code.
The id of your image is myImage, but you wrote var image = document.getElementById('Light'); which result on undefined.
As mentioned by PierreDuc, you missed parenthesis around if conditions.
Take a look at this example : https://jsfiddle.net/1wjn943x/
var images = [
"http://openphoto.net/thumbs2/volumes/mylenebressan/20120720/openphotonet_11.jpg",
"http://openphoto.net/thumbs2/volumes/sarabbit/20120322/openphotonet_DSCF5890.JPG",
"http://openphoto.net/thumbs2/volumes/Sarabbit/20120117/openphotonet_gerberadaisy3.jpg"
];
var index = 0;
var img = document.getElementById("myImage");
document.getElementById("button").addEventListener('click', function() {
// Next image.
index = (index + 1) % images.length;
// Setting `src`attribute of <img>.
img.src = images[index];
});
This is the easiest way to change the image.
Simply set the image source to be the next image in the array. You need to use the mod operator to loop from the end; back to the beginning.
Array - Index Pointer
var imageEl = document.getElementById('Light');
var index = 0;
var images = [
"http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
"http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
"http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
"http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow"
];
function changeImage() {
imageEl.src = images[index++ % images.length]; // Set and increment the image index.
}
changeImage();
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
Map - Linked Pointer
var imageEl = document.getElementById('Light');
var currImage = '';
var images = {
red : {
src : "http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
next : 'rambo'
},
rambo : {
src : "http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
next : 'green'
},
green : {
src : "http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
next : 'yellow'
},
yellow : {
src : "http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow",
next : 'red'
}
};
function changeImage() {
(function(img) {
imageEl.src = img.src; // Set the image source to the current image.
currImage = img.next; // Set current image as the next image.
}(images[currImage || 'red']));
}
changeImage();
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>
Class - Circular Iterator
var CircularIterator = function(iterable) {
this.iterable = iterable || [];
this.index = 0;
this.get = function(index) {
return this.iterable[index] || this.next();
};
this.size = function() {
return this.iterable.length;
};
this.incr = function() {
return this.index = ((this.index + 1) % this.size());
};
this.next = function() {
return this.get(this.incr());
};
this.first = function() {
return this.get(0);
};
this.last = function() {
return this.get(this.size() - 1);
};
};
var imageEl = document.getElementById('Light');
var iterable = new CircularIterator([
"http://placehold.it/150x150/FF0000/FFFFFF.jpg?text=Red",
"http://placehold.it/150x150/0000FF/FFFFFF.jpg?text=Rambo",
"http://placehold.it/150x150/00FF00/FFFFFF.jpg?text=Green",
"http://placehold.it/150x150/FFFF00/FFFFFF.jpg?text=Yellow"
]);
function changeImage() {
imageEl.src = iterable.next(); // Set and increment the image index.
}
imageEl.src = iterable.first(); // Set the current image to the first.
<img id="Light" width="150" height="150">
<br />
<button type="button" onclick="changeImage()">Click me to change the light in the sequence!</button>

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>

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