Issue with onclick event not being triggered by Javascript function inside constructor

My current challenge involves implementing a function called makeHighlight within the SmartButton constructor. The purpose of this function is to execute whenever I click on the SmartButton object, which is represented by an image element. To achieve this, I have set the 'onclick' attribute to trigger the makeHighlight function. However, I am facing difficulties as it either does not run at all or runs immediately upon page load.


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');

Answer №1

By placing makeHighlight within the context of the SmartButton function, it cannot be accessed by newImg when clicked. To address this issue, consider implementing the following code snippet inside the SmartButton:

function makeHighlight() {
    newImg.setAttribute('src', highlightImage);
    console.log(this);
}
newImg.onclick = makeHighlight;

(ensure there are no brackets on the last line) and remove the following line:

newImg.setAttribute('onclick', "makeHighlight()");

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The margin on the right side is not functioning as expected and exceeds the boundary, even though the container is using the flex display property

I'm struggling to position the rating stars on the right side without them going outside of the block. I attempted using 'display: flex' on the parent element, but it didn't solve the issue(( Currently trying to adjust the layout of t ...

What is the method for toggling background URLs?

Currently, I am utilizing flaunt.js by Todd Moto for my navigation system. My goal is to seamlessly switch the hamburger image with another image when the mobile-menu is shown and hidden. Check out the demo here. For a detailed tutorial, visit this link. ...

The tooltips on a resized jQuery Flot chart are displaying in the incorrect location

Currently, I am utilizing the flot library for my chart. I am facing an issue with getting the correct tooltips to display when I scale the chart using this CSS rule: transform: scale(0.7); The flot source relies on the function findNearbyItem to locate ...

Resolving problems with jQuery auto-populating select dropdowns through JSON data

I am facing an issue with auto-populating a select dropdown using jQuery/JSON data retrieved from a ColdFusion CFC. Below is the code snippet: $(function(){ $("#licences-add").dialog({autoOpen:false,modal:true,title:'Add Licences',height:250,wid ...

Capture the current state of a page in Next.js

As I develop my Next.js application, I've encountered an architectural challenge. I'm looking to switch between routes while maintaining the state of each page so that I can return without losing any data. While initialProps might work for simple ...

Is the Vue-portal enabled conditionally?

I am looking to include some additional information in the navbar (parent component) using Vue Portal. So, within a component, I can use the following code: <portal to="navbar"> <b-button>Some option</b-button> </portal&g ...

How to prevent npm from being accessed through the command prompt

I recently began working on a ReactJs project. However, I am facing an issue where after starting npm in Command Prompt, I am unable to enter any text. Should I close the cmd window or is there a way to stop npm? You can now access your project at the fol ...

When using react, it is not possible to have a <span> element as a child of a <

I designed a custom select dropdown feature for use in a redux-form within a react-redux application. The dropdown functions well, with no performance issues, but I am encountering a warning in the browser. Warning: validateDOMNesting(...): <span> c ...

Why won't my Java servlet code execute?

included the directory structure To facilitate adding two numbers and displaying the result upon clicking a submit button, I developed a straightforward Java servlet. This servlet retrieves the necessary information when called. The development environmen ...

What role do colors and tables play in Javascript?

Preparing for my upcoming Web Development exam, I stumbled upon an intriguing question: Here's how I tackled it: function pallete() { var components = ["00", "33", "66", "99", "CC", "FF"]; var context = document.body; var ...

How can the useEffect Hook be utilized to perform a specific operation just one time?

My goal was to have a modal popup appear if the user moves their cursor outside of the window. I experimented with the following code: React.useEffect(() => { const popupWhenLeave = (event) => { if ( event.clientY <= 0 || ...

Establishing connections in neo4j with the neo4j-nodejs API

I encountered an error while creating a relationship between two nodes that were generated within the code. Can someone advise me on the correct arguments for the function below and its proper formatting? node1.createRelationshipTo(node2, "some", {age:" ...

Dealing with unresolved promises in async/await functions

What is the best approach for handling unresolved promises? For instance: class Utils { static async thisFunctionOnlyResolvesWhenPassed2AndNeverRejects(number: number) { return new Promise((resolve, reject) => { if(number === 2 ...

I am currently having issues with the mustache syntax in vuejs, as it is not functioning properly

Having an issue with Vue.js where the mustache syntax isn't working properly. <!DOCTYPE html> <html> <head> <title>index</title> <script src="https://cdn.jsdelivr.net/npm/<a href="/cdn-cg ...

By executing array1.splice(1,1), I am deleting elements from array2 that was generated by copying array1 with array1.slice(0)

I was working with JSON data and converted it into an array of objects. Then, I assigned that array to another array using the .slice(0) method. However, I encountered an issue where when I tried to remove an element from the assigned array, it also remov ...

Prevent ESLint from linting files with non-standard extensions

My .estintrc.yaml: parser: "@typescript-eslint/parser" parserOptions: sourceType: module project: tsconfig.json tsconfigRootDir: ./ env: es6: true browser: true node: true mocha: true plugins: - "@typescript-eslint" D ...

The mysterious unknown variable dynamically imported: ../views/Admin/Home.vue in Vue3-vue-router4 has sparked curiosity

When utilizing Vue3, Vuerouter4, and Vite I am attempting to import components and routes into the vue router, but I am encountering an error (only for the route that contains children in my paths): This is my router code: import { createRouter, crea ...

Is it possible that the images are unable to load on the page

The frontend code successfully retrieves the image links sent by the backend but encounters issues displaying them. Despite confirming that the imgUrl data is successfully fetched without any hotlink protection problems, the images are still not appearing ...

Error: Unable to apply filter on this.state.pokemon due to invalid function

My goal is to fetch data from the PokeAPI and iterate through the array of information that is returned. I begin by setting my state to an empty array, then proceed to make the API call and retrieve data from the response, adding it to my pokemon state. ...

Error in THREE.js: Unable to access property 'lib' from an undefined source (THREE.ShaderUtils.lib["normal"])

I have been working on the challenges provided in the WebGL introductory book by Oreilly. Encountered a runtime error with the following code snippet. After searching online, it seems like I am the only one facing this issue. Could you please assist me in ...