Adjust the background color of child divs when the parent div is being hovered over

I am facing a challenge with my current setup:

<div class="parent">
  <div class="child">
  </div>
  <div class="child">
  </div>
  <div class="child">
  </div>
</div>

My goal is to change the background color of all children simultaneously when the mouse hovers over any one of them. I attempted the following:

<script type="text/javascript">
 $(function() {
    $('.parent').hover( function(){
       $(this).css('background-color', 'gray');
    },
     function(){
      $(this).css('background-color', 'red');
    });
 });
 </script>

Unfortunately, the color change does not apply to the children <div>s.

Is it possible to target the descendants of "this"? I have multiple sets like this in a row, so I believe using "this" is necessary to avoid calling each parent by id. I am thinking of something like this:

<script type="text/javascript">
 $(function() {
    $('.parent').hover( function(){
       $(this "div").css('background-color', 'gray');
    },
     function(){
      $(this "div").css('background-color', 'red');
    });
 });
 </script>

However, I am struggling to make it work - all the examples I found on jquery.com use the id selector and do not involve "this".

Thank you for your help!

Answer №1

Why bother with JavaScript if you're not aiming for IE6? You can achieve the desired effect with just pure CSS:

.container, .item {
    background-color:blue;
}

.container:hover, .container:hover .item {
    background-color:yellow;
}

Answer №3

One way to locate elements is by using the .find() method.

$(this).find('div').css('background-color','red');

For more information, you can visit http://api.jquery.com/children/

Answer №4

Give this a shot:

 $(function() {
    $('.parent').hover( function(){
       $(this).children("div").css('background-color', 'gray');
    },
     function(){
       $(this).children("div").css('background-color', 'red');
    });
 });

See it in action: http://jsfiddle.net/zt9M6/

Answer №5

When using $(), make sure to provide either a string as a selector (div) or a DOM element (this). To target all div elements within the scope of this, consider using the following approach:

<script type="text/javascript">
 $(function() {
    $('.parent').hover( function(){
       $("div", this).css('background-color', 'gray');
    },
     function(){
      $("div", this).css('background-color', 'red');
    });
 });
 </script>

Source: http://api.jquery.com/jQuery/#jQuery1

Answer №6

Style it using CSS classes

.container .element{
    background-color: blue;
}

.hover-effect .element{
    background-color: green;
}

$(.container').hover(function() {
    $(this).addClass("hover-effect"):
},
function(){
    $(this).removeClass("hover-effect");
});

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

Obtain the model value using Yii jQuery and then proceed to submit the form

Within the _form.php view, there is a presence of $model and a CActiveForm $form. I implemented JavaScript code to compare the value of $model->publication_date with the current date. If they are identical, the form will be submitted automatically. Othe ...

Save the JWT token securely within a closure

Someone mentioned that the recommended way to store JWT tokens is as follows: access_token in the application memory (like closures) refresh_token in cookie entries (HttpOnly) Currently, my access_token is stored in localStorage and used for checking aut ...

Obtain picture from firebase utilizing react Js

I have attempted multiple methods to download images from Firebase, but the download URL is not functioning as expected. Instead of downloading the image directly, it opens in a new tab. The function used in Firebase: export async function addMedia(locati ...

"Utilize jQuery's append method to dynamically add elements to the DOM and ensure

I am currently facing an issue with my AJAX function that appends HTML to a page using the jQuery append method. The HTML being appended is quite large and contains cells with colors set by CSS within the same document. The problem I'm encountering i ...

What is the best way to transfer the value of a <span> element to a different <div> using jQuery or JavaScript

Is there a way to move or copy the price and insert it into the <div class="info"> using jQuery? The code I'm currently using is returning an unexpected result of "102030". jQuery(document).ready(function($) { $(document).ready ...

"Exploring the process of assigning input data to a different variable within a Vue component

Reviewing the code snippet I currently have: <template> <div> <input v-model.number="money"> <p>{{ money }}</p> </div> </template> <script> name: 'MyComponent', data () { ...

The div-tag is not displaying the background image as expected

I'm completely stumped. My goal was to create my own gallery, but right from the start, I hit a roadblock: Trying to display an image as a background in a <div>. I've tried everything, searched high and low on the internet, combed through s ...

What is the process for displaying a document file in an iframe that is returned from a link's action?

I have a main page called index.cshtml. This page displays a list of document files along with an iframe next to it. My goal is to load the selected document file into the iframe when I click on any item in the list. However, currently, when I click on a d ...

Combine es6 imports from the identical module using an Eslint rule or plugin

Looking to consolidate my ES6 imports from a single module into one for my React project. For example: import { Title } from "@mantine/core"; import { Center } from "@mantine/core"; import { Divider } from "@mantine/core"; T ...

The loading cursor in IE7 flickers incessantly, causing the webpage to lag and become un

When I move my cursor and click in text fields, the page becomes unresponsive and shows a wait cursor. If you're curious to see this issue in action, check out this video. This problem is specific to IE7. I've attempted to identify any ajax re ...

The error code 405 (Method Not Allowed) occurs in Ajax when the action field is empty or identical to the current page

Special thanks to @abc123 for sharing the code below in one of their posts: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-1.9.1.js"></script> </head> <body> <form id="formoid" a ...

performing a jQuery AJAX call from a UIWebView during the initial launch of the app following installation

We have a uiWebview that uses jquery for an ajax request to log in. It functions flawlessly on mobile safari and all browsers. However, when the application is launched for the first time after installation, the ajax request seems to be sent out but no re ...

Json with ExtJs columns data is fully populated

I am having trouble with displaying columns in my jsp which fetches json data. I am retrieving this json data in my javascript and using Ext.data.JsonStore but the columns are not showing up as expected. Here is the code for the store: store = new Ext.da ...

Border utilities in Bootstrap 4 provide easy ways to add borders

I have been searching for a solution, but I can't seem to find it. Bootstrap 4 offers utility classes for adding and removing borders, but is there a way to define the border width or style like solid or dashed? <span class="border"></span&g ...

Are there any other benefits to utilizing the Decorator pattern besides enhancing dynamic behavior?

Currently, I am diving into the intricacies of the Decorator design pattern and a particular thought has been nagging at me. What if we simply had one base class with boolean values representing its features? Consider this example: Imagine a textview tha ...

Sort through an array of objects by their respective values within another array of nested objects

I am struggling to filter out positions from the positions array that are already present in the people array. Despite trying different combinations of _.forEach and _.filter, I can't seem to solve it. console.log(position) var test = _.filter(posi ...

Angular's innerHTML dilemma

Within my Angular service, I have implemented three methods as shown below: public loadLiveChat() { let url: string; url = this.appConfig.config.liveAgent.liveAgentScriptUrl; this.dynamicallyLoadScript(url); ...

Leveraging the reduce method in processing JSON data

Here is the JSON data I have: { "meta": { "totalPages": 13 }, "data": [{ "type": "articles", "id": "3", "attributes": { "title": "AAAAA", "body": "BBBB", "created": "2011-06-2 ...

Is comparing strings in JavaScript as efficient as comparing numbers?

Considering creating a JavaScript enum library involves deciding how to store the values, I'm at a crossroads. Should I opt for speed in comparison or prioritize readability during debugging by using strings or numbers? While objects are an option too ...

My jQuery code is encountering issues with the .each loop functionality

I have encountered an issue with the code snippet below, which is intended to hide the "IN STOCK" phrase on specific vendors' product pages. Upon testing, I noticed that the loop doesn't seem to be executing as expected when using console.log. Ca ...