Changing separate images one at a time with onclick - javascript

I'm currently trying to use JavaScript to produce a page with multiple image files that I want to change individually and separately when I click on them. The best way I can to describe it is if you can imagine a set of playing cards face down, and I want to be able to click each one and have it change to a different image, and to be able to click again to change back.
Please see JavaScript and code below that I have done so far. The script works on my first image, but not on any further images.
HTML:
<img id="imgOne" onclick="changeImageOne()" src="click_here.png" height="100" width="100">
<img id="imgTwo" onlick="changeImageTwo()" src="click_here.png" height="100" width="100">
JavaScript:
var changeImageOne = function() {
var imageOne = document.getElementById('imgOne');
if (imageOne.src.match("i.jpg")) {
imageOne.src = "click_here.png";
} else {
imageOne.src = "i.jpg";
}
}
var changeImageTwo = function() {
var imageTwo = document.getElementById('imgTwo');
if (imageTwo.src.match("l.jpg")) {
imageTwo.src = "click_here.png";
} else {
imageTwo.src = "l.jpg";
}
}

typo # onlick, it is onclick
var changeImageOne = function() {
var imageOne = document.getElementById('imgOne');
if (imageOne.src.match("i.jpg")) {
imageOne.src = "click_here.png";
} else {
imageOne.src = "i.jpg";
}
alert(imageOne.src);
}
var changeImageTwo = function() {
var imageTwo = document.getElementById('imgTwo');
if (imageTwo.src.match("l.jpg")) {
imageTwo.src = "click_here.png";
} else {
imageTwo.src = "l.jpg";
}
alert(imageTwo.src);
}
<img id="imgOne" onclick="changeImageOne()" src="click_here.png" height="100" width="100">
<img id="imgTwo" onclick="changeImageTwo()" src="click_here.png" height="100" width="100">

JavaScript :
<script>
function SWAPImage(idv,oldimg,newimg){
document.getElementById(idv).attributes.src.value=newimg;
document.getElementById(idv).attributes["alt-src"].value = oldimg;
}
</script>
HTML :
<img class="image" src="a.jpg" alt-src="a_other.jpg" id="img1" onClick="SWAPImage(this.id,this.attributes.src.value,this.attributes['alt-src'].value)" />
<img class="image" src="b.jpg" alt-src="b_other.jpg" id="img2" onClick="SWAPImage(this.id,this.attributes.src.value,this.attributes['alt-src'].value)" />
<img class="image" src="c.jpg" alt-src="c_other.jpg" id="img3" onClick="SWAPImage(this.id,this.attributes.src.value,this.attributes['alt-src'].value)" />
I used alt-src attribute to store other image on it.When click on any image.It swap src with alt-src.

Related

Javascript: unable to add delay and load functionality

I have a following code which displays the clicked image in the below div using pause JS. I wanted to added some delay during which i show a loader/spinner on screen for few seconds and then show the pic. But i am getting a problem, that when I click image loader appears for a sec(no matter the delay ms e.g. 5000) and then image loads in the browser, not there div, Below is my HTML code for section I am targeting.
function showPic(whichpic) {
var source = whichpic.getAttribute("href");
var placeholder = document.getElementById("placeholder");
placeholder.setAttribute("src",source);
if (!document.getElementById("imageDescription")) return false;
if (whichpic.getAttribute("title")) {
var text = whichpic.getAttribute("title");
} else {
var text = "";
}
var imageDescription_p = document.getElementById("imageDescription_p");
var imageDescription_d = document.getElementById("imageDescription_d");
var imageDescription = document.getElementById("imageDescription");
if (imageDescription.firstChild.nodeType == 3) {
imageDescription.firstChild.nodeValue = text;
// imageDescription_p.textContent=prob;
imageDescription_d.innerHTML=test
imageDescription_d2.innerHTML=test1
}
document.getElementById('placeholder').style.display='block'
document.getElementById('loading').style.display = 'none';
// if (imageDescription_p.firstChild.nodeType == 3) {
// imageDescription_p.firstChild.nodeValue = text;
// }
return false;
}
function preparePlaceholder() {
if (!document.createElement) return false;
if (!document.createTextNode) return false;
if (!document.getElementById) return false;
if (!document.getElementById("imagegallery")) return false;
var placeholder = document.createElement("img");
placeholder.setAttribute("id","placeholder");
placeholder.setAttribute("src","./img/resources/neutral_1.jpg");
placeholder.setAttribute("alt","your image goes here");
placeholder.style.padding='20px'
placeholder.style.marginBottom='50px'
var description = document.createElement("p");
description.setAttribute("id","description");
var desctext = document.createTextNode("Choose an image");
description.appendChild(desctext);
var imageDescription= document.createElement('h1');
imageDescription.setAttribute("id","imageDescription");
var imageDescription_p= document.createElement('p');
imageDescription_p.setAttribute("id","imageDescription_p");
var imageDescription_d= document.createElement('div');
imageDescription_d.setAttribute("id","imageDescription_d");
var imageDescription_d2= document.createElement('div');
imageDescription_d2.setAttribute("id","imageDescription_d2");
var desctext = document.createTextNode("");
imageDescription.appendChild(desctext);
var heading= document.getElementsByTagName('h3')
var gallery = document.getElementById("imagegallery");
// insertAfter(description,heading);
insertAfter(description,gallery)
insertAfter(placeholder,description);
insertAfter(imageDescription,placeholder);
insertAfter(imageDescription_p,imageDescription);
insertAfter(imageDescription_d,imageDescription_p);
insertAfter(imageDescription_d2,imageDescription_d);
}
function prepareGallery() {
if (!document.getElementsByTagName) return false;
if (!document.getElementById) return false;
if (!document.getElementById("imagegallery")) return false;
var gallery = document.getElementById("imagegallery");
var links = gallery.getElementsByTagName("a");
for ( var i=0; i < links.length; i++) {
links[i].onclick = function() {
document.getElementById("imagegallery").style.display='none'
document.getElementById('placeholder').style.display='none'
document.getElementById('loading').style.display = 'block';
// document.getElementById('placeholder').style.display = 'none';
// setTimeout(calculateResults, 2000);
// e.preventDefault();
// return setTimeout(showPic(this), 2000)
// return showPic(this);
setTimeout(()=>showPic(this),5000)
}
}
}
addLoadEvent(preparePlaceholder);
addLoadEvent(prepareGallery);
<div id="content">
<h3>Select Images Below</h3>
<ul id="imagegallery">
<li>
<a href="./img/team/t1.jpg" title="Black Man in Glasses" >
<img src="./img/team/t1.jpg" alt="the band in concert" height="75px" width="75px" />
</a>
</li>
<li>
<a href="./img/team/t2.jpg" title="Black Man in Glasses" >
<img src="./img/team/t2.jpg" alt="the band in concert" height="75px" width="75px" />
</a>
</li>
<li>
<a href="./img/team/t3.jpg" title="Brown Women">
<img src="./img/team/t3.jpg" alt="the guitarist" height="75px" width="75px" />
</a>
</li>
<li>
<a
href="./img/team/t4.jpg" title="White Women">
<img src="./img/team/t4.jpg" alt="the audience" height="75px" width="75px" />
</a>
</li>
</ul>
<div id="loading">
<img src="img/loading.gif" alt="">
</div>
</div>
If you are getting confused by my version of code you can look at here. I am using the same code and flow here, except that i want to implement loader/spinner and hide(ul images get hidden after click) functionality.
The placeholder element you are creating is being created in the document:
var placeholder = document.createElement("img");
You need to place a div in your html code where you want the image to display, then you can append the placeholder image to that div:
document.getElementById('id of the div you insert').appendChild('block you want to insert')

JavaScript : onchange function causes error/ didn't work

The Following code will add File upload and preview field.
<b>This single img works but not in js</b> <br>
<img id="img" alt="your image" width="100" height="100" />
<input type="file" onchange="document.getElementById('img').src = window.URL.createObjectURL(this.files[0])">
<br/>
No of Img <input type="text" id="noi" name="noi" value="" onkeyup="addFields()">
<br />
<script>
function addFields(){
// Number of inputs to create
var number = document.getElementById("noi").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
var array = ["CRICTICAL","HIGH","LOW","INFO"];
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=1;i<=number;i++){
var img = document.createElement("img");
img.width="100";
img.height="100";
img.id="img "+i;
var upload = document.createElement("input");
upload.type="file";
//This part is Not Working_______________
upload.onchange="document.getElementById(img.id).src = window.URL.createObjectURL(this.files[0])";
//________________________________________
container.appendChild(img);
container.appendChild(upload);
container.appendChild(document.createElement("br"));
}
}
</script>
<div id="container"/>
Problem :
Without the Container appendChild function the code works fine, you can see it in the first three lines of code.
You have to run a function inside upload.onchange. Something like this:
upload.onchange= function () {
document.getElementById(img.id).src = window.URL.createObjectURL(this.files[0])
}
Other way to do:
upload.addEventListener('change', function () {
document.getElementById(img.id).src =
window.URL.createObjectURL(this.files[0])
})
Problem Solved
Working Fine.
All image fields can able to preform upload and preview function of 'n' fields.
<b>This single img works but not in js</b> <br>
<img id="img" alt="your image" width="100" height="100" />
<input type="file" onchange="document.getElementById('img').src = window.URL.createObjectURL(this.files[0])">
<br/>
No of Img <input type="text" id="noi" name="noi" value="" onkeyup="addFields()">
<br />
<script>
function addFields(){
// Number of inputs to create
var number = document.getElementById("noi").value;
// Container <div> where dynamic content will be placed
var container = document.getElementById("container");
var array = ["CRICTICAL","HIGH","LOW","INFO"];
// Clear previous contents of the container
while (container.hasChildNodes()) {
container.removeChild(container.lastChild);
}
for (i=1;i<=number;i++){
var img = document.createElement("img");
img.width="100";
img.height="100";
img.id="img "+i;
var upload = document.createElement("input");
upload.type="file";
upload.id="upload "+i;
//Working_______________
upload.onchange=upload.onchange= function () {
var img_id=this.getAttribute('id');
var imgId = img_id.charAt(7) ;
document.getElementById("img "+imgId).src = window.URL.createObjectURL(this.files[0])
}
//________________________________________
container.appendChild(img);
container.appendChild(upload);
container.appendChild(document.createElement("br"));
}
}
</script>
<div id="container"/>

memory game how to flip current card with set attribute

I'm making a memory game and trying to flip a card to its image value. when I click on the card it should change the image to the current image in the array but for some reason, it's not working.
JS
var faces = []; //array to store card images
faces[0] = 'images/king-of-diamonds.png';
faces[1] = 'images/king-of-hearts.png';
faces[2] = 'images/queen-of-diamonds.png';
faces[3] = 'images/queen-of-hearts.png';
var cardsInPlay = [];
var checkForMatch = function (cardId) {
if (faces[cardId] === faces[cardId + 1]) {
console.log("You found a match!");
} else {
console.log("Sorry, try again.");
}
}
var flipCard = function (cardId, name) {
document.getElementById('image1')[this].getAttribute("id").src = faces[cardId]
checkForMatch();
}
HTML
<div>
<img onclick="flipCard(1,this)" id="image1" src="images/back.png" alt="Queen of Diamonds">
<img onclick="flipCard(2,this)" id="image1" src="images/back.png" alt="Queen of Hearts">
<img id="image3" src="images/back.png" alt="King of Diamonds">
<img id="image4" src="images/back.png" alt="King of Hearts">
</div>
You should avoid using the same id in different elements. Id is thought to be unique and so you should not have more elements with the same id in the entire page.
At this point you can directly do:
var flipCard = function (cardId, name) {
document.getElementById('image1').src = faces[cardId];
checkForMatch();
}

jQuery hide all images except first

I have a data collection thats gets rendered from the server. This is how the HTML might looks like:
<div>
<img class="image_98" alt="..." height="..." src="..." width="..." />
</div>
<div>
<img class="image_99" alt="..." height="..." src="..." width="..." />
</div>
<div>
<img class="image_99" alt="..." height="..." src="..." width="..." />
</div>
<div>
<img class="image_100" alt="..." height="..." src="..." width="..." />
</div>
<div>
<img class="image_100" alt="..." height="..." src="..." width="..." />
</div>
<div>
<img class="image_100" alt="..." height="..." src="..." width="..." />
</div>
The image class is dynamic depending on the id of the image in the database. How can I hide all images except the first one of every class?
In this example I only want to see the first "image_98", "image_99" and "image_100" class.
You can do it like this, using attribute selector [attribute="value"] and each() method
var img=$('[class^="image_"]');
img.hide(); //hide all image
img.each(function(){
$('.'+this.className).eq(0).show(); // show first image in each class
});
Use
show() , to show the selected item
hide() , to hide the selected item.
Old school method :
var slice = Array.prototype.slice,
imgs = slice.call(document.getElementsByTagName('img')),
img, ct, cls;
while (img = imgs.shift()) {
if (cls === img.className) {
ct = img.parentNode;
ct.parentNode.removeChild(ct);
} else {
cls = img.className;
}
}
Yuk indeed...
Using jQuery, I would do quite the same :
var prevCls;
$('img').each(function () {
var cls = $(this).attr('class'); // I have a doubt about .className support
if (prevCls === cls) {
$(this.parentNode).remove(); // or .hide() if preferred
} else {
prevCls = cls;
}
});
Advantage comparing to the accepted answer : a single loop.
Here is another method using recursivity - quite close to the first one :
(function deldup(list, prevCls) {
var item = list.shift();
if (item.className !== prevCls) {
prevCls = item.className;
} else {
item = item.parentNode;
item.parentNode.removeChild(item);
}
if (list.length) {
deldup(list, prevCls);
}
})(
Array.prototype.slice.call(
document.getElementsByTagName('img')
)
);
Advantage : no global variables.
In case images are mixed :
(function deldup(list, cls) {
var item = list.shift();
if (!cls[item.className]) {
cls[item.className] = true;
} else {
item = item.parentNode;
item.parentNode.removeChild(item);
}
if (list.length) {
deldup(list, cls);
}
})(
Array.prototype.slice.call(
document.getElementsByTagName('span')
), {} // notice this empty object
);
Demo : http://jsfiddle.net/wared/QpZD5/.

JavaScript Toggle Image by clicking on Img

Im trying to toggle between two images but need the js to work with many different images. How do I make it with a parameter with the id? This is what I got so far:
JS
function changeIt(id)
{
var theImg = document.getElementsByTagName('img')[0].src;
var x = theImg.split("/");
var t = x.length-1;
var y = x[t];
if(y=='red.gif')
{
document.images.boxcolor1.src='./pics/green.gif'
}
if(y=='green.gif')
{
document.images.boxcolor1.src='./pics/red.gif'
}
}
HTML
<img src='./pics/green.gif' name='boxcolor1' id='boxcolor1' border='0' />
<img src='./pics/green.gif' name='boxcolor2' id='boxcolor2' border='0' />
<img src='./pics/green.gif' name='boxcolor3' id='boxcolor3' border='0' />
As you can see now it only works for the first image (boxcolor1).. I want it to work for all images by the name or id tag.
Thanks for all the help!
Try:
function changeIt(id)
{
var theImg = document.getElementById(id),
x = theImg.src.split("/"),
t = x.length-1,
y = x[t];
if(y == 'red.gif')
{
theImg.src='./pics/green.gif'
}
if(y == 'green.gif')
{
theImg.src='./pics/red.gif'
}
}
Working example:
http://jsbin.com/ugofiz/edit

Categories

Resources