Can't change Image during onclick event in javascript - javascript

I have added image & button dynamically to a webpage. I wrote a "onclick" event, by which the image will be changed on clicking respective button. But the code doesn't work.
My code is;
<style>
.tableclass{
height:80px;}
.imgclass{
height:50px;
width:50px;} </style>
<script>
var img = new Image();
img.src = "Images/circle.png";
img.className = 'imgclass';
window.onload = function init() {
for(var i=0;i<5;i++)
{
var container = document.getElementById('body');
var table = document.createElement('table');
table.className = 'tableclass';
var tr = document.createElement('tr');
var td = document.createElement('td');
var btn = document.createElement('input');
btn.type = 'button';
btn.className = 'buttonclass';
td.appendChild(btn);
td.appendChild(img);
tr.appendChild(td);
table.appendChild(tr);
container.appendChild(table);
}
}
btn.onclick = function(){
document.getElementsByClassName('imgclass').src = "Images/square.jpeg";
};
</script>
<body id="body"></body>

You are adding an event to...
boton.onclick
But I think your variable is named buton - so you need to use:
buton.onclick
Also, as this is running in the loop, you probably want to add the onclick event to each one you create (so put the event binding inside the loop).
Here is a running version of the script:
function getImage() {
var img = new Image();
img.src = "Images/circle.png";
img.className = 'imgclass';
return img;
}
function getRow() {
var img = getImage();
var tr = document.createElement('tr');
var td = document.createElement('td');
var buton = document.createElement('input');
buton.type = 'button';
buton.className = 'buttonclass';
buton.onclick = function(){
img.src = "Images/square.jpeg";
};
td.appendChild(buton);
td.appendChild(img);
tr.appendChild(td);
return tr;
}
var container = document.getElementById('body');
var table = document.createElement('table');
table.className = 'tableclass';
for(var i = 0; i < 5 ; i++) {
table.appendChild(getRow());
}
container.appendChild(table);
You can see it running on JSFiddle.

getElementsByClassName returns a collection, not a single element.
You may do this :
var imgs = document.getElementsByClassName('imgclass');
for (var i=0; i<imgs.length; i++) imgs[i].src = "Images/square.jpeg";
But it would be probably cleaner to give an id to your image and use getElementById.
Note also that you seem to hesitate on the spelling of botón/boton/buton and that will make it hard for the code to work. You should see errors in the console.

There boton has an accent the first time you use it...and why are you using a for loop? I think an array of images could work and every time you click it increments a counter which changes the image. Also use .jpg not .jpeg

This is closer to the original -- I just removed the for loop because I didn't see the need for it...
<style>
.tableclass{
height:80px;}
.imgclass{
height:50px;
width:50px;} </style>
<script>
var count = 0;
var images = [];
images[0] = "Pictures/1.jpg";
images[1] = "Pictures/2.jpg";
images[2] = "Pictures/3.jpg";
images[3] = "Pictures/4.jpg";
var img = new Image();
img.src = images[count];
img.className = "imgclass";
window.onload = function init() {
var container = document.getElementById('body');
var table = document.createElement('table');
table.className = 'tableclass';
var tr = document.createElement('tr');
var td = document.createElement('td');
var button = document.createElement('input');
button.type = 'button';
button.className = 'buttonclass';
button.onclick = function(){buttonClick();}
td.appendChild(button);
td.appendChild(img);
tr.appendChild(td);
table.appendChild(tr);
container.appendChild(table);
}
function buttonClick(){
if(count < images.length - 1){
count++;
}else{
count = 0;
}
img.src = images[count];
};
</script>
<body id="body"></body>

Related

How to add an onclick event to an img element created in javascript

Basically creates a table with the image and the name uploaded by the user, now i want to let the user choose which images he wants trough a onclick event, but once i upload an image the function "myfunction" runs without clicking the img
function handleFiles() {
var inputElement = document.getElementById("input");
var fileList = inputElement.files;
var NameFile = [];
for(var i = 0; i < fileList.length; i++){
NameFile=fileList[i].name;
var x = document.createElement("Table");
x.setAttribute("id", "galeria" + (i));
document.body.appendChild(x);
// imagens
var Img = document.createElement("tr");
Img.setAttribute("id", "ImgTr" +(i));
document.getElementById("galeria" +(i)).appendChild(Img);
var Imgz = document.createElement("td");
var img =document.createElement("img");
img.src = window.URL.createObjectURL(fileList[i]);
img.height = 50;
img.onload = function(){
window.URL.revokeObjectURL(this.src);
}
img.onclick = myfunction(); // onclick event attateched to img
element
Imgz.appendChild(img);
document.getElementById("ImgTr" + (i)).appendChild(Imgz);
// files names
var y = document.createElement("tr");
y.setAttribute("id", "Tr" + (i));
document.getElementById("galeria" +(i)).appendChild(y);
var z = document.createElement("td");
var t = document.createTextNode(NameFile);
z.appendChild(t);
document.getElementById("Tr" + (i)).appendChild(z);
}
}
function myfunction(){
alert("hello");
}
Problem solved thanks to #CertainPerformance
/.../
img.onclick = myfunction; // onclick event attateched to img
element
/.../

Passing image array values and changing image source onclick

OK, so finally the penny dropped (loud clunk!) on the click issue I was having here Append dynamic div just once and a JSFiddle issue. The code now shows user a choice of pics once per node clicked. Phew.
However, now my img.src=e.target.src line is having trouble accessing the other images in the array. Only the last image in the array will add to the table. I think this is because the allImages.onclick event should be inside the loop?
I have tried that and then img is showing up as undefined. I'm guessing that is because the loop (and therefore the function) is running before var img is declared? I think it is an issue with the order of things.
All help appreciated.
var makeChart = function () {
var table = document.createElement('table'),
taskName = document.getElementById('taskname').value,
header = document.createElement('th'),
numDays = document.getElementById('days').value, //columns
howOften = document.getElementById('times').value, //rows
row,
r,
col,
c;
var myImages = new Array();
myImages[0] = "http://www.olsug.org/wiki/images/9/95/Tux-small.png";
myImages[1] = "http://a2.twimg.com/profile_images/1139237954/just-logo_normal.png";
for (var i = 0; i < myImages.length; i++) {
var allImages = new Image();
allImages.src = myImages[i];
var my_div = document.createElement("div");
my_div.id = "showPics";
document.body.appendChild(my_div);
var newList = document.createElement("ul");
newList.appendChild(allImages);
my_div = document.getElementById("showPics");
my_div.appendChild(newList);
my_div.style.display = 'none';
}
header.innerHTML = taskName;
table.appendChild(header);
header.innerHTML = taskName;
table.appendChild(header);
function addImage(col) {
var img = new Image();
img.src = "http://cdn.sstatic.net/stackoverflow/img/tag-adobe.png";
col.appendChild(img);
img.onclick = function () {
my_div.style.display = 'block';
allImages.onclick = function (e) { // I THINK THIS IS THE PROBLEM
img.src = e.target.src;
my_div.style.display = 'none';
img.onclick=null;
};
}
}
for (r = 0; r < howOften; r++) {
row = table.insertRow(-1);
for (c = 0; c < numDays; c++) {
col = row.insertCell(-1);
addImage(col);
}
}
document.getElementById('holdTable').appendChild(table);
document.getElementById('createChart').onclick=null;
}
Well, the problem seems to stem from different parts. First of all,
for (var i = 0; i < myImages.length; i++) {
var allImages = new Image();
allImages.src = myImages[i];
var my_div = document.createElement("div");
my_div.id = "showPics";
document.body.appendChild(my_div);
var newList = document.createElement("ul");
newList.appendChild(allImages);
my_div = document.getElementById("showPics");
my_div.appendChild(newList);
my_div.style.display = 'none';
}
This loop creates a new div for EACH image in myImages, then appends a ul to that div, and finally appends the Image for the current image to the ul.
The question of what document.getElementById('showPics') returns, since there are as many divs with the id showPics appended to body as myImages.length, has a mystical magical answer which should never be spoken, or even thought, of again.
Why not do the sensible thing and create one singular happy div outside the loop? Append a single ul child to it, outside the loop. Then proceed to append as many li as you want in the loop.
var my_div = document.createElement('div');
my_div.id = 'showPics';
var newList = document.createElement('ul');
my_div.appendChild(newList);
for var i = 0; i < myImages.length; i++) {
...
var li = document.createElement('li');
li.appendChild(allImages);
newList.appendChild(li);
...
}
my_div.style.display = 'none';
Now, my_div is the one and only div containing the images. So, the click event handlers can toggle its visibility safely.
Second,
function addImage(col) {
var img = new Image();
img.src = "http://cdn.sstatic.net/stackoverflow/img/tag-adobe.png";
col.appendChild(img);
img.onclick = function () {
my_div.style.display = 'block';
allImages.onclick = function (e) { // I THINK THIS IS THE PROBLEM
img.src = e.target.src;
my_div.style.display = 'none';
img.onclick=null;
};
}
}
allImages references the same Image object now that you are out of the loop, which happens to be the last image in myImages. So, only the last image in myImages will register the handler to a click event. To solve this problem, we make a new variable.
var sel = null; //This comes before my_div
Now, we add the click handler to allImages inside the loop so that every image in myImages gets a piece of the pie, as they say.
for var i = 0; i < myImages.length; i++) {
var allImages = new Image();
allImages.src = myImages[i];
allImages.onclick = function (e) {
if(sel !== null) {
sel.src = e.target.src;
my_div.style.display = 'none';
sel.onclick=null;
sel = null;
}
};
...
}
And finally, adjust addImage so that sel can be set when the image is clicked.
function addImage(col) {
...
img.onclick = function () {
my_div.style.display = 'block';
sel = img;
}
...
}
That's all there is to it! Example.
Note that, if you comment out sel.onclick = null, you can change a particular cell's image as many times you like.
Your addImage() function makes a direct reference to the allImages variable. One problem is that since you were using (and reusing) that variable in a for loop earlier in the code it is only going to retain the last value that was assigned to it. So no matter how many times you call addImage() it's always adding the onclick function to the last image that allImages pointed to.
I'd also suggest renaming the allImages variable. That's a very misleading name because it in fact only ever represents a single image.
Hope that helps!

Change node image with image from array onclick

I am displaying the images from the array. I want the user to be able to choose an image from the array and for it to replace the current image img.src in the table. I have managed to show the user the image choices when a cell is clicked, but unsure where to go from here. I have tried a clickhandler on the array image but the alert is only showing when last image in array is clicked. Confused. All help appreciated.
function addImage (col) {
var img = new Image(); // Note that a new img variable will be declared each time this function is called
img.src = "../www/images/TEST.png";
col.appendChild(img);
img.onclick = function () {
var myImages = new Array();
myImages[0] = "../www/images/TEST3.png";
myImages[1] = "../www/images/TEST2.png";
myImages[2] = "../www/images/TEST4.png";
for (var i = 0; i < myImages.length; i++) {
var allImages = new Image();
allImages.src=myImages[i];
var newList = document.createElement("ul");
var newContent = allImages;
newList.appendChild(newContent);
my_div = document.getElementById("showPics");
document.body.insertBefore(newList, my_div);
};
allImages.onclick = function(){
alert("the click is working");//it is but only for the last image...grrrrr
};
//this.src = ????;
};
};
for (r = 0; r < howOften; r++) {
row = table.insertRow(-1);
for (c = 0; c < numDays; c++) {
col = row.insertCell(-1);
addImage(col);
};
};
document.getElementById('holdTable').appendChild(table);
};
For starters, you need to move your click assignment inside your loop:
function addImage(col) {
var img = new Image(); // Note that a new img variable will be declared each time this function is called
img.src = "../www/images/TEST.png";
col.appendChild(img);
img.onclick = function() {
var myImages = new Array();
myImages[0] = "../www/images/TEST3.png";
myImages[1] = "../www/images/TEST2.png";
myImages[2] = "../www/images/TEST4.png";
for (var i = 0; i < myImages.length; i++) {
var allImages = new Image();
allImages.src = myImages[i];
var newList = document.createElement("ul");
var newContent = allImages;
newList.appendChild(newContent);
my_div = document.getElementById("showPics");
document.body.insertBefore(newList, my_div);
allImages.onclick = function(e) {
img.src = e.target.src;
};
};
//this.src = ????;
};
};
for (r = 0; r < howOften; r++) {
row = table.insertRow(-1);
for (c = 0; c < numDays; c++) {
col = row.insertCell(-1);
addImage(col);
};
};
document.getElementById('holdTable').appendChild(table);
};
...but the code you have will re-assign your click handlers every time an image is clicked, as well as recreating your DOM (HTML) elements. You might want to consider instead having it only hide/show my_div on subsequent clicks.

Stop div from adding on every click

I have a table with a background image that, when clicked, displays other images for the user to choose from. This is working and appears or hides on click events. However, when the user clicks to add a second image the menu of images appears again (as it should) but twice. I have commented out a solution I tried. I thought on first click I could display my_div and then delete it in allImages.onclick. This is throwing up a null error in Chrome, probably understandably. The problem here is similar. Hope I added link correctly. Anyway, advice or help appreciated.
function addImage(col) {
var img = new Image();
img.src = "../www/images/TEST.png";
col.appendChild(img);
img.onclick = function () {
var myImages = new Array();
myImages[0] = "../www/images/TEST3.png";
myImages[1] = "../www/images/TEST2.png";
myImages[2] = "../www/images/TEST4.png";
for (var i = 0; i < myImages.length; i++) {
var allImages = new Image();
allImages.src = myImages[i];
var newList = document.createElement("ul");
newList.appendChild(allImages);
my_div = document.getElementById("showPics");
my_div.appendChild(newList);
my_div.style.display = 'block';
allImages.onclick = function (e) {
img.src = e.target.src;
my_div.style.display = 'none';
//var element = document.getElementById("showPics");
//element.parentNode.removeChild(element);
};
}
};
};
for (r = 0; r < howOften; r++) {
row = table.insertRow(-1);
for (c = 0; c < numDays; c++) {
col = row.insertCell(-1);
addImage(col);
}
}
document.getElementById('holdTable').appendChild(table);
I modified your code adding ul to hold all img. It works, but could be better.
function addImage(col) {
var img = new Image();
img.src = "../www/images/TEST.png";
col.appendChild(img);
var myImages = new Array();
myImages[0] = "../www/images/TEST1.png";
myImages[1] = "../www/images/TEST2.png";
myImages[2] = "../www/images/TEST3.png";
var container = document.createElement("ul"); //ul to simplify hide/show
container.style.display = "none";
for (var i = 0; i < myImages.length; i++) {
var newList = document.createElement("li");
var im = document.createElement("img");
im.src = myImages[i];
newList.appendChild(im);
im.onclick = function () {
img.src = this.src;
};
container.appendChild(newList);
}
col.appendChild(container);
col.onclick = function () {
if (container.style.display == "none")
container.style.display = "block";
else
container.style.display = "none";
};
}

why the onclick event doen't work from an external .js file?

I have wrote a .js file in wich I have create a table, buttons, etc. My aplication is a photo album and everything is created on this file, the html build up properly with all the buttons but when I give click on the buttons, the buttons don't change the images.
The code of the .jp file is:
var dp = document.createElement("img");
function changeImage()
{
var list = document.getElementById('optionlist');
dp.src = list.options[list.selectedIndex].value;
alert(dp.src);
}
function prevImage()
{
var list = document.getElementById('optionlist');
alert("Llega a prev");
if(list.selectedIndex == 0)
{
list.selectedIndex = list.options.length-1;
}
else
{
list.selectedIndex--;
}
changeImage();
}
function firstImage()
{
var list = document.getElementById('optionlist');
list.selectedIndex = 0;
changeImage();
}
function nextImage()
{
var list = document.getElementById('optionlist');
if(list.selectedIndex == list.options.length-1)
{
list.selectedIndex = 0;
}
else
{
list.selectedIndex++;
}
changeImage();
}
function lastImage()
{
var list = document.getElementById('optionlist');
list.selectedIndex = 9;
changeImage();
}
function start() {
var txt1,txt2,txt3,txt4,txt5,txt6,txt7,txt8,txt9,txt10,txt11;
//get the reference for the body
var body = document.getElementsByTagName("body")[0];
//alert("creates a <table> element and a <tbody> element");
var tbl = document.createElement("table");
tbl.setAttribute("align","center");
tbl.setAttribute("border","0");
var tbl2 = document.createElement("table");
tbl2.setAttribute("align","center");
tbl2.setAttribute("border","0");
var tblBody = document.createElement("tbody");
var tblBody2 = document.createElement("tbody");
//alert("creating <p>");
txt11 = document.createTextNode(" JavaScript Module ");
var downtxt = document.createElement("p");
downtxt.setAttribute("align","center");
downtxt.appendChild(txt11);
//alert("creates <input> elements");
var first = document.createElement("input");
first.setAttribute("value", " << ");
first.setAttribute("type", "button");
first.onClick = firstImage;
var previous = document.createElement("input");
previous.setAttribute("type", "button");
previous.setAttribute("value", " < ");
previous.onClick = "JavaScript:prevImage()";
var last = document.createElement("input");
last.setAttribute("value", " >> ");
last.setAttribute("type", "button");
last.onClick = "JavaScript:lastImage()";
var next = document.createElement("input");
next.setAttribute("value", " > ");
next.setAttribute("type", "button");
next.onClick = "JavaScript:nextImage()";
//alert("creating images options and <select>");
var op1 = document.createElement("option");
var op2 = document.createElement("option");
var op3 = document.createElement("option");
var op4 = document.createElement("option");
var op5 = document.createElement("option");
var op6 = document.createElement("option");
var op7 = document.createElement("option");
var op8 = document.createElement("option");
var op9 = document.createElement("option");
var op10 = document.createElement("option");
op1.setAttribute("value","1.jpg");
txt1 = document.createTextNode("First Image");
op1.appendChild(txt1);
op2.setAttribute("value","2.jpg");
txt2 = document.createTextNode("Second Image");
op2.appendChild(txt2);
op3.setAttribute("value","3.jpg");
txt3 = document.createTextNode("Third Image");
op3.appendChild(txt3);
op4.setAttribute("value","4.jpg");
txt4 = document.createTextNode("Fourth Image");
op4.appendChild(txt4);
op5.setAttribute("value","5.jpg");
txt5 = document.createTextNode("Fifth Image");
op5.appendChild(txt5);
op6.setAttribute("value","6.jpg");;
txt6 = document.createTextNode("Sixth Image");
op6.appendChild(txt6);
op7.setAttribute("value","7.jpg");
txt7 = document.createTextNode("Seventh Image");
op7.appendChild(txt7);
op8.setAttribute("value","8.jpg");
txt8 = document.createTextNode("Eight Image");
op8.appendChild(txt8);
op9.setAttribute("value","9.jpg");
txt9 = document.createTextNode("Ninth Image");
op9.appendChild(txt9);
op10.setAttribute("value","10.jpg");
txt10 = document.createTextNode("Tenth Image");
op10.appendChild(txt10);
var slct = document.createElement("select");
slct.setAttribute("id","optionlist");
slct.onChange = changeImage;
slct.appendChild(op1);
slct.appendChild(op2);
slct.appendChild(op3);
slct.appendChild(op4);
slct.appendChild(op5);
slct.appendChild(op6);
slct.appendChild(op7);
slct.appendChild(op8);
slct.appendChild(op9);
slct.appendChild(op10);
//alert("Creating rows and columns for the tables");
var td1 = document.createElement("td");
td1.setAttribute("align","center");
td1.setAttribute("colspan","3");
dp.setAttribute("name","mainimage");
dp.setAttribute("border","1");
dp.setAttribute("align","center");
td1.appendChild(dp);
var tr1 = document.createElement("tr");
tr1.setAttribute("align","center");
tr1.appendChild(td1);
var td2 = document.createElement("td");
td2.setAttribute("align","left");
td2.appendChild(first);
td2.appendChild(previous);
var td3 = document.createElement("td");
td3.setAttribute("align","center");
td3.appendChild(slct);
var td4 = document.createElement("td");
td4.setAttribute("align","right");
td4.appendChild(next);
td4.appendChild(last);
var tr2 = document.createElement("tr");
tr2.appendChild(td2);
tr2.appendChild(td3);
tr2.appendChild(td4);
//alert("adding all the elements to the table");
tblBody2.appendChild(tr1);
tblBody.appendChild(tr2);
tbl2.appendChild(tblBody2);
tbl.appendChild(tblBody);
//alert("adding table to <body>");
body.appendChild(tbl2);
body.appendChild(tbl);
body.appendChild(downtxt);
changeImage();
}
and the html code is:
<html>
<head>
<title>Photo Album </title>
<style>
p, td {color:blue;font-family:verdana;font-size:8pt}
h1 {color:black;font-family:verdana;font-size:14pt}
</style>
<script type = "text/javascript" src = "PAScript.js" language = "javascript">
</script>
</head>
<body onLoad="start()" bgcolor = "grey">
</body>
</html>
It somebody can help me please, I don't have idea how to make work the buttons of my application
Thanks
When you're setting onclick by javascript, it's a function reference instead of a string.
previous.onClick = "JavaScript:prevImage()";
should be
previous.onclick = prevImage;
Fix your other assignments to follow this pattern. Also onclick is all lower case and is case sensitive.
As long as we're on the topic, the preferred way to register event handlers is
standards compliant browsers
previous.addEventListener('click', prevImage, false);
IE
previous.attachEvent('onclick', prevImage);

Categories

Resources