Adjust the color of the background when hovering with the cursor

I am currently working on a project with a menu of buttons that dynamically changes based on the elements in a list. For instance, if my list contains ["A", "B", "C"], then I would have a menu with 3 buttons.

Here is how I display the buttons using a javascript plugin:

    html += '<div id="buttonGallery">'

    // add buttons for each element in the list
    _.map(myList, function(letters, ind) {   
      html += '<div id="button_' + letters + '" class="buttons">';
      html += '<p>' + letters + '</p></div>';
    }); 

I am facing an issue where I need to change the background-color of each button when hovered over by the user. The challenge is that each button does not have a set id, making it difficult to target them individually in CSS.

I want my solution to be flexible and applicable to different scenarios where the list may contain different elements like "D" and "E". In such cases, there might be only 2 buttons, each with unique hover colors.

If anyone has suggestions on how to approach this problem, I would greatly appreciate your input!

Below is a simplified version of the code I am working with, but please note that it assigns explicit ids to the buttons which is not ideal for my generalizable solution. In this example, all buttons turn red when hovered over.)

<html lang="en" dir="ltr">

<head>
  <meta charset="utf-8">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <style media="screen">
    .buttons {
      width: 150px;
      height: 50px;
      border: solid 2px black;
      text-align: center;
      color: black;
      cursor: pointer;
      background-color: white;
      margin: 2px;
    }

    #buttonGallery {
      margin: 10px;
      padding: 10px;
      border: solid 2px black;
      width: 155px;
    }

    .buttons:hover {
      background-color: red !important;
      border: solid 3px black !important;
    }

    .selected {
      background-color: red !important;
      border: solid 3px black !important;
    }
  </style>
</head>

<body>

  <div id="buttonGallery">
    <div class="buttons">
      <p>A</p>
    </div>
    <div id="button_B" class="buttons">
      <p>B</p>
    </div>
    <div id="button_C" class="buttons">
      <p>C</p>
    </div>

  </div>

  <script type="text/javascript">
    $('.buttons').click(function() {
    $(".buttons").not($(this)).removeClass("selected");
    $(this).toggleClass("selected");
  </script>
</body>

</html>

(If you require further clarification, feel free to provide feedback on how I can improve the clarity of my post. Thank you!)

Answer №1

One possible way to accomplish this task is as follows:

   let $buttons = $('<div id="buttonGallery">');
    let myList = ["A", "B", "C", 'D'];
    let myColors = ['red', 'green', 'blue', 'red'];
    
    
    myList.map(function(letter, index) {   
      let $button = $('<div></div>')
      .addClass('buttons')
        .attr('id', 'button_' + letter)
        .html( '<p>' + letter + '</p>')
        .on('mouseenter', function(){
          $(this).css('background', myColors[index]);
        }).on('mouseleave', function() {
        $(this).css('background', 'transparent');
        });
      $buttons.append( $button );
    });
        
    $('body').append( $buttons );
.buttons {
  width: 150px;
  height: 50px;
  border: solid 2px black;
  text-align: center;
  color: black;
  cursor: pointer;
  background-color: white;
  margin: 2px;
}

#buttonGallery {
  margin: 10px;
  padding: 10px;
  border: solid 2px black;
  width: 155px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

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

Converting nested lists into arrays: A deep dive into Eloquent JavaScript's fourth chapter

I'm stuck on this exercise and could really use some help to complete it. Can someone show me how to finish it and explain the solution? Thanks a lot! There's a list value called "values" that needs to be converted into an array format like [1, ...

Can I keep using ng-repeat multiple times in my code?

Working on a AngularJS application that involves handling a complex JSON file with multiple nested arrays and objects. My query is: Is it appropriate to use ng-repeat repeatedly for accessing the data from the JSON? <div ng-repeat="parent in parents"&g ...

Transforming code into syntax-highlighted HTML

Seeking a Python module that can convert code written in various coding languages into syntax-highlighted HTML code. Want something akin to the code tag functionality used on StackOverflow. ...

How can we deliver pure JS, HTML, and CSS content without relying on static HTML pages?

Looking to create a fast app prototype without using React or Vue? I'd like to avoid simply making an html and js file imported within it. Can npm packages, SCSS be used while programming vanilla Javascript minus a framework? ...

CSS Styling for Adjusting Table Cell Widths

In my HTML table, I am trying to set the overall width while ensuring that the label column does not become too wide. Although it functions correctly in Firefox 4, IE 9 seems to be completely ignoring the width property. <html> <head> <sty ...

Tips for displaying an uploaded image using the Valums file uploader

I recently implemented the Andrew Valums File Uploader on my website and it's functioning as expected. I am now looking to modify it so that instead of displaying just the uploaded filename and size, it will show the uploaded picture directly in the b ...

try out testing with the mock declaration in Jasmine test

My service involves loading a variable from a JavaScript file fetched from a CDN (without a typedef). To handle this, I have created a declaration for the variable: declare const externalValue: string; @Injectable() export class Service { ... Everythi ...

jQuery's capability to select multiple elements simultaneously appears to be malfunctioning

I am dynamically creating div elements with unique ids and adding span elements with specific CSS properties. $(".main").append("<div class=largeBox id=" + counter + "</div>"); $(".largeBox").append("<span class=mainTitle></span>"); ...

The addDays method cannot be used with date variables

Having two TextBoxes where I input 2 dates and try to retrieve an array of dates between them. Here is the code I'm using: $(".txtto").change(function () { var dates = new Array(); var dateto = new Date(); ...

Set the background color of the container row to extend the full width, encompassing

I am working on a grid container and I want to change the background color of the second row within it. Check out my Fiddle This is the HTML markup: <div class="totalContainer totalContainer__space"> <div class="totalContainer__ ...

Problem encountered with AngularJS html5mode URL functionality

I am encountering an issue with my AngularJS application that does not contain any nodeJS code. The problem lies in removing the # from the URL and I have implemented ui-routes for routing. 'use strict'; var app = angular.module('myapp&apos ...

Updating the JWT token in Angular 6 and making a new request with the updated token

When my JWT authentication token expires (verified by the backend), I need to call a refresh token API and resend the last failed request due to the expired token. I have an Interceptor in place, but I must update the authentication header before sending ...

Tips on utilizing a local file as a background image URL

How can I modify my CSS to link to a local file path like C:\xampp\htdocs\Folder instead of the URL https://source.unsplash.com/1600x1050/?nature. I am currently using Bootstrap 4 and below is my CSS code: .jumbotron{ background: ...

The behavior of AngularJS checkbox and ng-change is definitely puzzling

I am facing an issue with my array structure: { key : 'abc', color: 'Red', show: true } <div ng-repeat="x in myArray"> <input type="checkbox" ng-model="x" ng-change="changeShow($index)" checked="checked" /> ...

Issue with showing second page in form post using Express.js: node.js, express.js and jade

I am a beginner in node and express and I created a small app, but it's not functioning properly. When I submit a post on page 1, the app does not display page 2. Here is the structure and code of my project: / /controller/controllers.js /node_module ...

Generating a list of values separated by commas from a Microsoft Excel column after applying regular expressions

I have an Excel column that I need to convert into CSV format. A JavaScript regex has been provided to apply on the column values: var regex = new RegExp("[^a-z0-9',.]+","gi"); return input.replace(regex, "_").replace(/_+/g, "_").replace(/^_|_$|^&bso ...

Troubleshooting: Why isn't the Access-Control-Allow-Origin header functioning correctly?

I'm currently trying to address the HTTP OPTIONS method by including an Access-Control-Allow-Origin header that mirrors the information in the Origin header from the request. Unfortunately, it seems like this approach isn't functioning properly, ...

DIV that floats and P element

When utilizing the float attribute, two div elements align next to each other, but two paragraph elements do not; causing the 'p' element to display oddly. Interestingly, when floating two 'div' elements and two 'p' elements, ...

ChartJS v2: Displaying scale value based on click coordinates for time scale

I am having an issue with a time-based line chart where I am trying to retrieve the values for each scale at the click coordinates. In my ChartJS options, I have defined an onClick function: onClick: function(event, elementsAtEvent) { console.log(eve ...

Attempting to maintain the main navigation highlighted while browsing through the secondary navigation

I am facing a small issue that seems like it should be an easy fix, but I can't seem to figure it out. While working on my site, I'm having trouble keeping the parent navigation highlighted when scrolling through the sub-menu. If you hover over ...