I’m trying to run a function called makeHighlight within my constructor SmartButton. makeHighlight is supposed to run whenever I click on the SmartButton object (an image element) which is why I set the attribute ‘onclick’ to makeHighlight. I can’t get it to work, it either doesn’t run at all or runs instantaneously when the page loads.
function SmartButton(buttonId, defaultImage, highlightImage, helpMsg) {
var newLink = document.createElement('a');
newLink.setAttribute('href', '#');
var newImg = document.createElement('img');
newImg.setAttribute('src', defaultImage);
newImg.setAttribute('id', buttonId);
newImg.setAttribute('onclick', "makeHighlight()");
document.body.appendChild(newLink);
newLink.appendChild(newImg);
this.buttonId = buttonId;
this.defaultImage = defaultImage;
this.highlightImage = highlightImage;
this.helpMsg = helpMsg;
function makeHighlight() {
newImg.setAttribute('src', highlightImage);
console.log(this);
}
}
button1 = new SmartButton('button1', 'button1off.jpg', 'button1on.jpg', 'sup');
You defined
makeHighlightin the scope ofSmartButtonfunction. ThusnewImgwhen clicked does not see it. Try this code (insideSmartButton):(note the lack of brackets in the last line) and remove this line: