Home > Software design >  Is it possible to run an onclick javascript function inside another javascript function?
Is it possible to run an onclick javascript function inside another javascript function?

Time:11-03

Currently learning javascript and was curious about this possibility. I have this code inside a .JS file

var x = document.createElement("IMG");
                    x.setAttribute("src", "helpimage.png");
                    x.setAttribute("width", "20");
                    x.setAttribute("height", "20");
                      x.setAttribute("alt", "help image");
                      x.setAttribute("id","image");
                    var row = document.createElement('div');
                    row.classList.add('row');
                    var label = document.createElement('div');
                        label.id = machineName   '-label';
                        label.classList.add('col-md-5');
                        label.innerHTML = humanName   ':';
                        label.appendChild(x);
                        label.onclick = function() {myFunction()};
                        
                    row.appendChild(label); 

and this function titled "MyFunction"

function myFunction() {
    document.getElementById(machineName   '-label').innerHTML = "YOU CLICKED ME!";
  }

What this code does is that first a function is called which creates a simple form element with a label. I attach a picture labeled "x" into the label. I would like to be able to click that label, with an onclick event, and then change it to whatever I want. (just testing here)

So once my first function generates my form, I then want to click my label and have it change to "YOU CLICKED ME".

Except when I click the picture nothing happens.

Can anyone tell me what I'm doing wrong?

picture of what I want to click. enter image description here

CodePudding user response:

Put the text that you want to replace in another nested element, rather than in the element that also contains the image.

var x = document.createElement("IMG");
x.setAttribute("src", "helpimage.png");
x.setAttribute("width", "20");
x.setAttribute("height", "20");
x.setAttribute("alt", "help image");
x.setAttribute("id", "image");
var row = document.createElement('div');
row.classList.add('row');
var label = document.createElement('div');
let machineName = "filename";
label.id = machineName   '-label';
label.classList.add('col-md-5');
let humanName = "File Name";
let text = document.createElement("span");
text.id = machineName   "-text";
text.innerHTML = humanName   ':';
label.appendChild(text);
label.appendChild(x);
label.onclick = function() {
  myFunction()
};

row.appendChild(label);
document.body.appendChild(row);

function myFunction() {
  document.getElementById(machineName   '-text').innerHTML = "YOU CLICKED ME!";
}
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related