What is the best way to alter the background of a div when hovering over a button in a separate div?

Looking to change the background of one div when hovering over a button in another div?

Hello, I have a task where I need to modify the background color of a specific div when a button below it is hovered over.

The setup involves having an image (a tshirt logo) displayed in a div. Below that, there are multiple colored buttons. The requirement is to change the background of the tshirt div when hovering over these buttons. I am struggling with this and open to solutions using JavaScript or CSS.

I found a resource which seemed helpful but unfortunately did not work for me: On a CSS hover event, can I change another div's styling?

Here is my code snippet:

<!DOCTYPE html>
  <html>
    <head>
      <style>
        body {
          background:grey;
        }

        #shirt {
          display: block;
        }
        
        #thumbnail1 {
          display: block;
        }

        #thumbnail1:hover {
          background:white;
        }

        #thumbnail1:hover > #shirt {
          background:green;
        }

        input[type="button"] {
          width: 9.090%;
          height: 4.090%;
          display:block;
          float:left;
          background:red;
        }
      </style>
    </head>
    <body>

      <section>
        <div align="center">
          <img style=" margin-left:10px;float:left; background:grey;" src="http://www.dudermang.com/cfaulk/3pigs.gif" width="95"/>
          <div align="center" id="shirt">
            <img style="float:none" src="http://www.dudermang.com/cfaulk/3pigs.png" alt="wpf" width="760"/>
            <img style="float:right;     background:grey;"src="http://www.dudermang.com/cfaulk/3pigs.gif" width="95"/>       
          </div>
        </div>

        <div style="padding-top:40px;">
          <?php
            echo'<div id="thumbnail1"><input type="button" style="background:#002B7A"/>    </div>';
            // Remaining PHP echoes for other buttons...
          ?>
        </div>
      </section>
    </body>
 </html>

Answer №1

If you want to achieve this effect using CSS, you'll need to be cautious about the structure of your div elements. However, a more reliable approach is to use a simple jQuery function that changes the background color of a tshirt div to match the button's background color when hovered over.

To implement this, make a slight adjustment to your php code by adding a class called trigger_color:

echo'<div class="trigger_color" id="thumbnail1"><input type="button" style="background:#002B7A"/></div>';

Then include the following jQuery function in your code:

$(document).ready(function(){
    $( ".trigger_color" ).hover(
      function() {
         $("#shirt").css("background-color", $("input", this).css("background-color"));
      }, function() {
          $("#shirt").css("background-color", "gray"); //back to normal
      }
    );
});

Answer №2

To begin, assign a unique Div id such as "mainDiv"

Next, create a hover event for a button and include the following code:

document.getElementById("mainDiv").style.backgroundColor = "newColor";

Answer №3

Assign unique identifiers to both your button and div elements. Define a class that represents the hover and default states, applying these states on mouseover and mouseout events triggered by the button.

There are more sophisticated methods available depending on the framework used, especially when considering classes unrelated to the transition. However, the following code presents the basic concept:

window.onload = function() {
   var myDiv = document.getElementById("unique-div-id"),
       myBtn = document.getElementById("unique-btn-id");

   myBtn.onmouseover = function(e) {
      myDiv.classList.add("hover-class");
   };
   myBtn.onmouseout = function(e) {
      myDiv.classList.remove("hover-class");
   };
};

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

JavaScript - What is the best way to add the same object value into an array?

After spending a few hours trying to figure out how to manage JSON data structured like this: [ { "value": "Osteonecrosis", "Diagnosis_Code": "DIAG002", "NamaCategory": "Primary Category", "FK_Diagnosis_Content_ID": 2 }, { "value ...

Utilizing JavaScript for Formatting and Comparing Dates

Here, I would like to compare the current date with a user-inputted date. <script type="text/javascript"> $(document).ready(function(){ $("#date").change(function(){ var realDate = new Date(); var startDate = new ...

Guide to making a Java Servlet for a specific jQuery.ajax () request?

In one of my files named wfd.proxy.js, I have the following code snippet: if (!WFD) { var WFD = {}; }; if (!WFD.Proxy) { WFD.Proxy = {}; }; WFD.Proxy = { SERVICE_URL : "/delegate/WFD/WFService?", PDF_SERVICE_URL : "/delegate/pdf-exporter?", ...

SignalR fails to trigger client callback function

Currently, I am diving into the world of SignalR and attempting to create a basic message notification system. However, despite my limited understanding of SignalR, I am unable to display the messages after submission. I have researched multiple blogs on ...

Tips for preventing flickering caused by set Interval in angular 2+

Displaying dynamic latitude and longitude data on Google Maps while using setInterval() function. Code snippet below: this.timer = setInterval(()=>{this.getMapData();},30000); An issue arises where the map flickers when updating the data with this.get ...

Issue with Discord.js voice connection destruction函数

I've been attempting to implement a "Stop" command using the @discordjs/voice package, but I'm encountering an error. Despite my efforts to add some error handling, the issue persists. Below is the code snippet: async function stop(message) { t ...

In the context of ReactJS, how should the src property be formatted within an img tag to reference a mapped json file correctly?

Currently, I am trying to incorporate images from a local JSON file into my component. These images need to correspond with the data obtained from an API call. The contents of my JSON file are as follows: [ { "id": 1, "dwarf" ...

ngMaterial flex layout not functioning properly

I can't seem to figure out why ngMaterial is not laying out my simple hello world app in a row. Despite checking the console for errors, I still can't see what I am doing wrong. I expected the content below to be displayed horizontally instead of ...

Adjusting the arrow direction upon clicking in a Select option

Is there a way to make the arrow move upwards when I open the select dropdown option? <select class="form-select" aria-label="Default select example"> <option selected>Choose an option</option> <option value="1">One</optio ...

Generate an interactive table: one segment featuring a title or tag - its corresponding rows and columns that change dynamically, followed by another similar segment

I'm attempting to generate a dynamic table with the following structure upon clicking a button (I can't include an image, so here is a sample code to illustrate what I'm aiming for, but I need everything to be dynamic in the actual scenario) ...

Tips for creating a conditional confirm dialog box in Asp.net using JQuery/Javascript

I have some jQuery and traditional JavaScript mixed together to validate a textbox on my ASP sample page. There is a button, a textbox, and a button_click event in the code behind. When the button is clicked, I want to show an alert if the textbox is empty ...

encountering validation error during transmission of data through POST request

Creating a Mongoose Model const mongoose=require('mongoose'); const validator=require('validator'); const employeeSchema=new mongoose.Schema({ name:{ type:String, required:true, trim:true }, email ...

When iterating through a table, an error occurs stating that the property "rows" is not available on type HTMLElement (

Issue Error TS2339 - Property 'rows' does not exist on type HTMLElement when looping through table in Angular 7 Encountering error when trying to loop through HTML table in Angular 7 Currently working with Angular 7 and facing an error while ...

Ways to stop a bootstrap modal from closing upon pressing the ESC key and if it is not in

Utilizing the Bootstrap modal to showcase details from my database, including text and image attachments. Upon clicking an image attachment, I focus a div element to display a full-screen view of that image. My goal is to allow the user to close the image ...

Ways to emphasize the four edges of a table cell using border-collapse collapse

I am trying to emphasize the borders of cells with the class active. The challenge arises from the fact that the table's border-collapse property is set to collapse, causing the top and left borders of cells (except for the leftmost and top row cells ...

collapse each <b-collapse> when a button is clicked (initially shown)

I am facing an issue with a series of connected b-buttons and b-collapse, all initially set to be visible (open). My goal is to hide them all when a toggle from my parent.vue component is activated - so upon clicking a button in the parent component, I wa ...

Limiting the character count in a textarea can be achieved by implementing the 'jQuery InlineEdit' feature

Currently, I am utilizing the jquery.inlineedit.js plugin for inline editing, and one of my requirements is to limit the maximum length of text within the textarea. I have attempted to use other popular jQuery scripts for this purpose, but unfortunately, I ...

Enabling and disabling HTML image input based on checkbox selection

I have utilized the code below to toggle the status of the image button between enabled and disabled modes using JQuery. Here is the code for a checkbox in Yii format: <?php echo CHtml::CheckBox('TermsAgreement','', array ('ch ...

Move Picture with Click (like the action on Google Maps)

Currently on the lookout for some code that will enable me to manipulate a floor plan in a manner reminiscent of the one showcased at whitehouse.gov I am in the process of coding a website that would benefit from integrating a similar function with their ...

"Encountering an issue when trying to choose a value from a select list using jQuery and the

What am I missing here or what is the correct approach to solve this? Take a look at the following code snippet: code snippet $(document).ready(function() { $(".metric_div").hide(); $("#solid_radio").click(function() { $("#solid").show(); ...