Is there a way to modify CSS styles for a child tag element after hovering over its parent?

Here are my HTML code segments:

<div class="div-builder">
    <div>
        <a href="#">
            <img src="/photos/20/Apple-Logo-icon.png" width="50" alt="Logo">
        </a>
        <h3>Title</h3>
        <i>sub-title</i>
    </div>
    <hr/>
    <p>Lorem Ipsum is simply dummy text of the printing and typesetting ...</p>
</div>

I want to create a hover effect for the .div-builder class where its background color changes according to this CSS:

.div-builder{ background-color: lightyellow; }

The desired result should look like the image shown in this link:

In addition, when hovering over the <img> tag, I also want its background color to change to lightyellow without affecting the .div-builder class. The result should be similar to the image in this link:

The <img> tag can be at any level within the .div-builder class. Similarly, the <h3>, <i>, or <p> tag should change their background color to lightyellow on hover, with the .div-builder class background color remaining unchanged. After hovering over the <p> tag, the result should resemble the image here:

Is there a way to achieve this hover effect using CSS?

Alternatively, how can I implement this click event instead of a hover effect using jQuery?

Answer №1

Hey there! Check out this answer I put together for you. Here is the link

function hoverEffect() {
      $(".div-builder")
        .find("h3,i,p,img,a")
        .hover(
          function () {
            $(this).css("background", "SpringGreen");
            $(".div-builder").css("background", "initial");
          },
          function () {
            $(this).css("background", "initial");
            $(".div-builder").css("background", "SpringGreen");
          }
        );
    }
    function resetHover() {
      $(".div-builder").css("background", "initial");
    }
<div class="div-builder" onmouseenter="hoverEffect()" onmouseleave="resetHover()">
      <div>
        <a href="#" width="100%">
          <img src="https://picsum.photos/id/4/300" alt="Logo">
        </a>
        <h3 class="">Title</h3>
        <i>sub-title</i>
      </div>
      <hr />
      <p>Lorem Ipsum is simply dummy text of the printing and typesetting ...</p>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Answer №2

Is this the style you're looking for?

body {
    background-color: rgba(173, 173, 173, 0.9);
}


.div-builder {
    background: white;
}

.div-builder div:hover {
    background: red;
}
    <div class="div-builder">
        <div>
            <a href="#">
                <img src="https://static.javatpoint.com/htmlpages/images/html-tutorial.png" alt="Logo">
            </a>
        </div>
        <div>
            <h3>Title</h3>
        </div>

    <div>
         <i>sub-title</i>    
    </div>
        <hr/>
        <div>
            <p>Lorem Ispsum is simply dummy text of the printing and typesetting ...</p>
        </div>
    </div>

Answer №3

If I understand correctly, your objective is to change the background of an element when hovering over it with the cursor. Achieving this is a simple task: It can be done using CSS by adding ":hover" to the CSS properties. For example, for a paragraph (p):

 p:hover {
      background-color: blue;
      font-size: 18px;
 }

Done! You can change the "p" selector to any ID or class you prefer.

See an example of changing background on hover. I hope this explanation was helpful.

If you want to change multiple elements at once when hovering over one:

.hoverThis:hover { background: green; }

Wrap the elements with a div container:

<div  class="hoverThis">
<p>This text will have a green background when hovered over.</p>
<p>And so will this one!</p>
</div>

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

Verifying the angular form without the need for a submit button

I'm currently utilizing angular.js form validation and I'm looking to implement validation without the use of a form submit button. Below is my HTML code: <form name="userForm"> <input type="hidden" ng-model="StandardID" /> < ...

Unexpected behavior occurs when ajax is added to an array for jQuery promise results

In my code, I have an each loop that makes individual AJAX requests and stores them in an array like this: var promises = []; $items.each(function(k, v) { promises.push( $.ajax({ url: ..., .... }) ); }); $.when.app ...

php json with multiple dimensions

Unable to retrieve the deepest values from my json object, which contains an array of images listed as: { "imgs":[ { "Landscape":{ "2":"DSCF2719.jpg", "3":"DSCF2775.jpg", "4":"IMG_1586.jpg", ...

How can I prevent my JSON object from serializing .NET nulls as "null" for object members?

I am currently utilizing WebMethods to retrieve an array of a custom class. When this array is returned from a Jquery .ajax call, it gets serialized into a JSON object that can be utilized with Javascript in my ASP.NET application. The issue I am facing is ...

Converting Variable Values to Element IDs in JavaScript: A Helpful Guide

Is it possible to declare a value in variable A and then access that value as an id in variable B using the method getElementById()? var A = 10; var B = document.getElementById(A); console.log(B); ...

Tracking monthly expenses in Yii2: Tips on managing your finances

Can someone help me with combining all expenses and income from each user into the same gridview and filter by month? I have two SQL queries that work individually, but I need assistance in using UNION or converting them for Yii2's ActiveDataProvider. ...

Having difficulty aligning ListItem to the right within a List

I am working with an array that contains objects which I need to display in ListItems of a List. My goal is to show these ListItems from the array Objects in a layout where odd numbers are on the left and even numbers are on the right. However, I am facing ...

Having trouble with blueprintjs icons not appearing as they should on certain pages

I have recently updated an older React application from blueprintjs version 1 to version 4 by following the documentation. However, I am now facing an issue where the icons are not displaying correctly as shown in the image below. Could someone please poi ...

Combining Three HTML Tags Into a Single Page

I currently have a standard PHP webpage that consists of the header, body, and footer sections. Within this setup, I use the following code: <?php include('header.html'); ?> The header.html file contains <html>... content </html& ...

Guide to Utilizing an AJAX Call to Populate a Line Graph in Highcharts

I've been attempting to create a line graph using highcharts in asp.net, but I'm having trouble getting anything to show up on the chart. Here's the code I have so far: var chart; $(document).ready(function () { chart = new Hig ...

Angular 8: ISSUE TypeError: Unable to access the 'invalid' property of an undefined variable

Can someone please explain the meaning of this error message? I'm new to Angular and currently using Angular 8. This error is appearing on my console. ERROR TypeError: Cannot read property 'invalid' of undefined at Object.eval [as updat ...

NodeJS instructs open(html) to execute first before any other code is executed

I am evaluating whether nodeJS is a suitable solution for a project I am working on during my internship. To summarize: I need the basicNode.js file to wait until the open('./basic.html') command has completely opened the browser and loaded its c ...

Verify if a request attribute has been established using jQuery

How can I determine if an attribute is present in a request object? I have specific error scenarios where an error message needs to be sent to the client side: Here is the servlet code snippet: request.setAttribute("error", "The following term was not fo ...

Tips for maintaining grid width when columns are rearranged in the column menu

Is it possible to stop jqgrid from changing its width to full screen after column selection? I attempted the code below, following guidance from How to change column name in column chooser pop up in jqgrid? My aim was to create a column switcher function ...

What steps should be taken to incorporate a user input space similar to the one found in the Wordpress new post section

I am looking to incorporate a user input section on my website similar to the one found in WordPress for creating new posts. I would like this area to have all of the same tools available, such as adding hyperlinks, bolding text, and uploading images. Ca ...

Nightwatch is a tool that allows you to interact with elements on a webpage by clicking on an element within

I have a scenario on my website where I have two separate div elements: <div class="wg-block" data-reactid="10" <div class="wg-header" data-reactid="11"/div> .... <h4 class='condition'> "Text" </h4> <div cl ...

The functionality of jQuery touch events on iOS devices is not functioning properly

I'm encountering issues with jQuery touch events on iOS devices. Here is my current script: $(document).ready(function(){ var iX = 0,iY = 0,fX = 0,fY = 0; document.addEventListener('touchstart', function(e) { ...

Displaying two paginated lists on a single page in a Rails application

In my Rails application, there is a page that displays two partials with paginated lists using AJAX. Controller code snippet: def show @movies = @movies.paginate(page: params[:page], per_page: 5) @books = @books.paginate(page: params[:page], p ...

What is the best way to incorporate polling into the code provided below? I specifically need to retrieve data from the given URL every 60 seconds. How should I go about achieving this

Can you assist me in integrating polling into the code below? <!DOCTYPE html> <html> <head> <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> <script src="https://code.highcharts.com/highcharts.js"> ...

Implement a slideshow feature that automatically changes a CSS attribute when preview images are shown

(Apologies for the perplexing title) My intention was to create a slideshow gallery, and I stumbled upon an example here: https://www.w3schools.com/howto/howto_js_slideshow_gallery.asp In this setup, you'll notice previews of images in a small bar b ...