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

Understanding JSON Parsing in Jade

I am facing a challenge with handling a large array of objects that I am passing through express into a Jade template. The structure of the data looks similar to this: [{ big object }, { big object }, { big object }, ...] To pass it into the Jade templat ...

Is the && operator being utilized as a conditional statement?

While following a tutorial, I came across this code snippet that uses the 'and' operator in an unusual way. Is this related to React? Can someone provide an explanation or share documentation that clarifies it? {basket?.length > 0 && ...

Experiencing an issue in Test Cafe when attempting to click on an invisible link using the Client Function

I need to find a way to click on an invisible button in HTML. I attempted to use ClientFunction, however I encountered an error related to the element. import { Selector,ClientFunction } from 'testcafe'; fixture('Clicking Invisible link&apo ...

Automatically selecting a row within Material-UI's data grid using React code

Currently, I am in the process of developing a React web application and utilizing DataGrid from Material-UI by Google. The grid displays based on the user's selection from a select list (e.g., if the select list consists of fruits and the user choose ...

Accessing getUserMedia within Internet Explorer 11 or utilizing MediaStream on IE 11

I am attempting to utilize the getUserMedia function in IE 11 with the help of the temasys plugin. However, IE does not support the MediaStream instance returned by getUserMedia. Below is a snippet of my code: import React from 'react' import { ...

Choosing a specific category to display in a list format with a load more button for easier navigation

Things were supposed to be straightforward, but unexpected behaviors are popping up all over the place! I have a structured list like this XHTML <ul class = "query-list"> <li class="query"> something </li> <li class="query" ...

Striking a balance between innovation and backward compatibility in the realm of Web Design/Development

Creating websites is my passion, and I enjoy optimizing them for various platforms, devices, and browsers. However, lately, I've been feeling frustrated. I'm tired of facing limitations in implementing my creative ideas due to outdated technolog ...

Dragging a stack of cards in a game of Solitaire using jQuery UI

I'm currently in the process of creating a Solitaire card game using Javascript. To enable dragging and dropping functionality for the cards, I am utilizing jQueryUI. In the example provided at http://jsfiddle.net/HY8g7/1/, you can see how the cards c ...

Troubleshooting KuCoin API: Dealing with Invalid KC-API-SIGN Error and FAQs on Creating the Correct Signature

I want to retrieve open orders for my account using the following code snippet: import { KEY, PASSWORD, SECRET } from "./secrets.js"; import CryptoJS from "crypto-js"; const baseUrl = 'https://api.kucoin.com' const endPointOr ...

Is there a way to halt or end an interval within a function triggered by useEffect()?

I am currently working on a countdown timer script using react.js. The timer displays a 3 or 5 seconds countdown before starting, with data for these countdowns coming from another component. I am facing an issue with controlling the main countdown timer ...

Is there a way to modify a specific item within a useState Array in Reactjs?

Having a useState hook that stores data in the following structure: const [orderData, setOrderData] = useState({ demoData1: '', demoData2: '', demoData3: '', demoArrayData: [{itemName: '', itemNumber: ...

Display a PHP file's content in an iframe without revealing the file path in the source code

In my project built with Laravel, I am utilizing PDF.JS to showcase various PDF documents. To secure the pdf path, I am attempting to conceal it by passing a PHP file in the src field of an iframe. In my view: <iframe id="reader" src="http://server.de ...

Create a PHP file with various functions and access them using jquery.post or jquery.get in a separate JavaScript file

Is there a way to call multiple PHP functions from my JavaScript file using Jquery.post? Typically, we use Jquery.post to call a PHP file and pass various values as post data. function new_user(auth_type, tr_id, user_name, email) { $.post("bookmark.p ...

Exploring the integration of methods in Vue.js components

Within my Vuejs project, I developed a new form component and integrated it into the main index component. This new component needs to validate certain fields, with validation methods already created in the parent component. However, I am facing difficulti ...

the conditional operator used without assigning the result to a variable

Exploring conditional operators on html canvas, I am seeking a streamlined approach to dynamically change stroke color based on conditions. Online examples have not provided a satisfactory solution in a single line of code. Currently, without using a cond ...

The controller in AngularJS fails to function properly after the initial page refresh

I am currently utilizing AngularJS in my hybrid Ionic application. Here is my controller: .controller('SubmitCtrl', function($scope) { console.log("It only works when the page is refreshed!"); }); The console.log function runs perfectly fine ...

Nodemailer fails to send out emails despite the absence of any error messages

I'm currently working on setting up a confirmation email feature for user sign-ups on my website. I've tackled similar tasks in the past, but this time I've hit a roadblock - the emails are not being sent, and there are no error messages to ...

I did not anticipate the React setState function to behave in the manner it did

While working on form validation for my page, I came across a tutorial showcasing a validation method that seems to be functioning correctly. However, there is one aspect that I am struggling to grasp. The tutorial suggests declaring a variable before the ...

Trouble arises when adding HTML elements to a Content Editable Div. Any text inputted after programmatically inserting HTML content will merge with the last HTML tag instead

I am currently working on a project that involves creating message templates within an app. Users have the ability to add placeholders for fields like names to these templates by clicking a button. They can also remove these placeholders by selecting an &a ...

jQuery for Implementing Pagination Across Multiple Tables

As a novice in the world of JavaScript and jQuery, I am struggling with implementing pagination for multiple tables on a single page. My goal is to have several tables that can be paginated using one navigation system. However, all my attempts so far have ...