What is the best way to adjust the color of a button element?

I've been troubleshooting the mouseover function of my JavaScript button object. The goal is to have a function call (specifically show()) within the object that detects the mouseover event and changes the button's color to grey. I suspect that there is an issue with the btnColor not updating in the original show() call, but I'm unsure how to fix it. What am I overlooking?

let canvas = document.getElementById("JScanvas");
let c = canvas.getContext("2d");
let mousePosition = {
  x: 0,
  y: 0
};

// some functions needed for this operation

function buildRect(fillColor, outlineColor, outlineSize, x, y, w, h) {

  if (fillColor && outlineColor) {
    c.beginPath();
    c.rect(x, y, w, h);
    c.fillStyle = fillColor;
    c.fill();
    c.lineWidth = outlineSize;
    c.strokeStyle = outlineColor;
    c.stroke();
  } else if (fillColor && !outlineColor) {
    c.beginPath();
    c.rect(x, y, w, h);
    c.fillStyle = fillColor;
    c.fill();
  } else if (!fillColor && outlineColor) {
    c.beginPath();
    c.rect(x, y, w, h);
    c.lineWidth = outlineSize;
    c.strokeStyle = outlineColor;
    c.stroke();
  }
}

function write(str, x, y, color, txtSize, font) {
  let size = txtSize.toString();
  c.font = size + "px" + " " + font;
  c.fillStyle = color;
  c.fillText(str, x, y);

}
// end of unnecessary functions

class button {
  // mouse is {canvs: canvas, mClicked: t/f, mPosition: mousePosition{x, y}}
  constructor(name, order, btnColor, x, y, w, h, txtColor, txtSize, m, f) {
    this.name = name;
    this.order = order;
    this.btnColor = btnColor;
    this.x = x;
    this.y = y;
    this.w = w;
    this.h = h;
    this.txtColor = txtColor;
    this.txtSize = txtSize;
    this.m = m;
    this.f = f;
  }

  show() {
    //***This is the problem area***
    // :(
    //change color when mouse over button...at least ideally... 
    this.m.canvs.addEventListener("mousemove", (event) => {
      console.log("hello there");
      /*if(this.x < this.m.mPosition.x && this.m.mPosition.x < this.x + this.w && this.y < this.m.mPosition.y && this.m.mPosition.y < this.y + this.h)
       */
      this.btnColor[0] = "grey";
    }); // end of problem area
    console.log(this.btnColor);
    if (!this.btnColor[0] && !this.btnColor[1]) {

      buildRect("transparent", false, 1, this.x, this.y, this.w, this.h);
    } else if (!this.btnColor[0]) {

      buildRect(false, this.btnColor[1], 1, this.x, this.y, this.w, this.h);
    } else if (!this.btnColor[1]) {

      buildRect(this.btnColor[0], false, 1, this.x, this.y, this.w, this.h);
    } else {
      buildRect(this.btnColor[0], this.btnColor[1], 1, this.x, this.y, this.w, this.h);

    }
    c.fillStyle = this.txtColor;
    let theString = String(this.txtSize) + "px Arial";
    c.font = theString;
    let width = Math.round(c.measureText(c.fillText(this.name, -1000, 0)).width);

    if (width > this.w) {
      let center = this.x + (this.w / 2);
      let newSize = this.w / width;
      c.font = String(this.txtSize * newSize);
      let newWidth = Math.round(newSize * width);
      c.textAlign = "center";
      c.textBaseline = "middle";
      c.fillText(this.name, this.x + (this.w / 2), this.y + (this.h / 2));

    } else {
      c.textAlign = "center";
      c.textBaseline = "middle";
      c.fillText(this.name, this.x + (this.w / 2), this.y + (this.h / 2));
    }
  }

  clickButton(mouseX, mouseY) {
    if (mouseX >= this.x && mouseX <= this.x + this.w && mouseY >= this.y && mouseY <= this.y + this.h) {
      return true;
    } else {
      return false;
    }
  }

  runf() {
    this.f();
  }
}

//getting mouse position 

function getMousePos(canvas, evt) {
  const rect = canvas.getBoundingClientRect();
  return {
    x: evt.clientX - rect.left,
    y: evt.clientY - rect.top
  };
}

canvas.addEventListener("mousemove", (evt) => {
  let r = getMousePos(canvas, event);
  mousePosition.x = r.x, mousePosition.y = r.y;
});

let mouse = {
  canvs: canvas,
  mClicked: false,
  mPosition: mousePosition
};

//button object to call: ("red" is the color of the button I am trying to change to grey)
let cookie = new button("cookie", 1, ["red", false], 50, 100, 150, 50, "black", 30, mouse, 2);
cookie.show();
<div id="JScanvas"></div>

Answer №1

To update the button color and redraw it, simply call this.show after changing the btnColor[0] value to "grey":

   if(this.btnColor[0] != "grey"){
      this.btnColor[0] = "grey";
      this.show();
   }

It is important to place the addEventListener block in the constructor to ensure that the event listener is only added once.

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

Ways to streamline redundant code by creating a higher order function that accepts different parameter types in TypeScript

Recently, I've been exploring the idea of refactoring this code into a higher order function using TypeScript to enhance its cleanliness and reusability. However, I'm facing quite a challenge in getting it to work seamlessly. import { DocumentDef ...

Sending data from an AJAX request to a Spring controller is a common task in web

var TableDatatablesEditable = function () { var handleTable = function () { function restoreRow(oTable, nRow) { var aData = oTable.fnGetData(nRow); var jqTds = $('>td', nRow); for (var i = 0, ...

What are the differences between performing a search in MongoDB (database component) and Node.js (server-side)?

1) My input consists of a string with approximately 30 comma-separated elements, such as str1, str2, str3, etc. This is represented by "INPUT_STRING". 2) Within my MongoDB collection, I have a set of "allowed_strings" which includes entries like str1, str ...

Steps for generating random numbers from a set of given numbers

I am faced with a scenario where I need to generate random numbers based on a given set of numbers. For instance, if I have an array num=[23,56,12,22], I would like to obtain a random number from this array. ...

I'm having trouble getting this angular expression to cooperate in Plunker. Can anyone shed some light on why {{ 843 / 42

I'm currently diving into Angular with the help of Plural Sight. The initial lesson dives into utilizing the ng-app directive. For those interested, here's a direct link to the Plunker editor: http://plnkr.co/edit/HIDCS8A9CR1jnAIDR0Zb?p=preview ...

What steps should be taken to fix the sinopia installation error?

While operating on redhat5.9, I encountered an exception related to 'make'. I am curious about what they are trying to create. It seems like it's related to JavaScript. [root@xxxx bin]# npm install -g sinopia --python=/usr/local/clo/ven/pyt ...

Using NodeJS to generate a multipart/mixed response

I am faced with a particular situation: creating a multipart/mixed response in NodeJS with full control over the communication on both ends to avoid interoperability issues. A JSON file containing a list of nodes describing each ZIP file, for example: [{ ...

"Prevent further button clicks by disabling it after the initial click with ActionRowBuilder in Discord.Js

Encountering a puzzling issue where I am unable to disable a button after it has been clicked. The option to disable the button does not seem to appear. When attempting to deactivate the button, I utilize the following function: const row = new ActionRowBu ...

Using jQuery to obtain the object context while inside a callback function

Suppose I have the following object defined: var myObj = function(){ this.hello = "Hello,"; } myObj.prototype.sayHello = function(){ var persons = {"Jim", "Joe", "Doe","John"}; $.each(persons, function(i, person){ console.log(this.h ...

Having trouble with the jQuery select2 AJAX functionality?

I've been experimenting with the jQuery select2 plugin and attempting to integrate AJAX with my external data, but unfortunately it's not working as expected. I'm curious if anyone can help me identify what mistake I might be making or if th ...

Minimize the length of the styled-component class name in the upcoming iteration

Dealing with styled-components in Next along with React can pose a challenge when it comes to ensuring proper rendering of the styled components. To tackle this issue, Next offers the compiler.styledComponents flag within the next.config.js file like so: c ...

Shapes in Three.js with multiple colors

As a newcomer to Three.js and webGL programming, I have successfully created a cone and a cylinder in my scene using the script provided below: var scene; var camera; var renderer; var createACone = function() { // Cone creation code here } var creat ...

The ConsoleCapture does not capture every console error for Sentry

Running into an issue capturing console errors with Sentry in a Next.js app. The problem arises from an error within a library that is inaccessible to us, specifically related to WebSocket "WebSocket is already in CLOSING or CLOSED state" This error is c ...

Discovering a device's model using JavaScript

How can I use Javascript to redirect users to different download pages based on their device model? ...

Error messages from the Outlook Web add-in are presented as helpful information

I need assistance in showing error notifications. Here is my code: Office.context.mailbox.item.notificationMessages.addAsync("error", { type: "errorMessage", message: "The add-in encountered an issue while processing this message." }) The respons ...

How does the Express server collaborate with Webpack middlewares to facilitate live reloading?

As I delve into node, express, and webpack, I find myself grappling with the concept of middleware. Upon examining the code snippet below, my current understanding is that once the web server is up and running and I navigate to http://localhost:7770/, the ...

How to automatically refresh a page in AngularJS after a POST request

After making a POST request, I attempted to use $state.reload in my controller to refresh the page. However, it is not updating the data on my page after registering the form. I have to manually refresh the page to see the correct data. .controller(' ...

Is there a way to align these buttons in the middle?

I am currently designing a webpage at The challenge I'm facing is: How can I center those buttons on the page? They need to remain centered and responsive even when the page is resized. Additionally, the spacing between the buttons is inconsistent. ...

What are the steps to make a div with no content inside?

Presently, I am dealing with 2 overlapping transparent div's each containing unique buttons and functionalities in the following manner: .item1{ height:10rem; width:10rem; position:absolute; border:0.5rem solid red; background-color:trans ...

What is the process of creating a model instance in a Nodejs controller?

Trying to work with the model object in Node using the sequelize module. It looks something like this: File structure: models index.js user.js controllers userController.js routes route.js ========================== models/users.js //created us ...