Updating the HTML class with JavaScript

My HTML class has two classes

$(document).ready(function() {
  $(".container").hover(function() {
    $('.green').addClass('display-on');
  });
  $(".container").mouseleave(function() {
    $('.black').removeClass('display-on');
  });
});
.black {
  background-color: black;
}

.green {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

  <div class="black">
    <h1>hello
      <h1>
  </div>

  <div class="green">
    <h1>hello
      <h1>
  </div>

</div>

I want the background color of container to be black when hovering over the h1 with class black.

And the background color of container should be green when hovering over the h1 with class green.

The code provided is not functioning correctly.

Answer №1

You can achieve this effect without using javascript by simply utilizing a few lines of CSS:

.black:hover {
  background-color: black;
}
.green:hover {
  background-color: green;
}

Correction: In case you are utilizing jQuery and my previous response was inaccurate, you can implement the following solution instead:

jsfiddle.net/L4t2kqhp

<div class="container"> 

 <div class="black">
   <h1>hello<h1>
  </div>

  <div class="green">
   <h1>hello<h1>
  </div>

</div>

$(document).ready(function() {   
    $(".black").hover(function() {
        $('.container').css("background-color", "black");
    }, function(){
    $('.container').css("background-color", "white");
});
    $(".green").hover(function() {
        $('.container').css("background-color", "green");
    }, function(){
    $('.container').css("background-color", "white");
});
});

Answer №2

Consider applying the following CSS for your styling:

.black:hover{
   background-color: black;
      }

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

Answer №3

If you're looking to achieve the desired outcome, one approach is to implement a hover function for each div. This function would then modify the parent .container class based on which div is being hovered over.

$(document).ready(function() {
  $(".green").hover(function() {
    $(this).closest('.container').toggleClass("green");
  });
  $(".black").hover(function() {
    $(this).closest('.container').toggleClass("black");
  });
});
.black {
  background-color: black;
}

.green {
  background-color: green;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">

  <div class="black">
    <h1>hello</h1>
  </div>

  <div class="green">
    <h1>hello</h1>
  </div>

</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

Error message in Angular when promises are not defined

Recently, I started working with promises for the first time. I have a function that returns a promise: public DatesGenerator(futercampaign: ICampaign, searchparam: any, i: number): ng.IPromise<any> { return this.$q((resolve, reject) => { ...

404 error occurs when attempting to load SVG files in Webpack 2

Recently, I delved into the world of webpack. However, I encountered a problem when trying to load an SVG file referenced in one of my CSS files. Despite trying various loaders such as this, that, and the other, I keep receiving a 404 error. Can anyone pro ...

Submission error in Ripple-lib: 'UnhandledPromiseRejectionWarning - DisconnectedError: not opened'

I'm encountering an issue while trying to send Ripple XRP using ripple-lib and rippled server. Whenever I submit the signed payment object, I receive an error message stating: UnhandledPromiseRejectionWarning: DisconnectedError: not opened. Below is ...

Center an element on the screen by dynamically adjusting its position according to the media query

As I work on creating a responsive website that can adapt to screens of various devices, I am facing a challenge. Each device has a different number of pixels, making it difficult to centrally position a div dynamically. Currently, I am using margin-left: ...

Modify the array value and access it outside of an asynchronous function

Is there a way to set values in an array from an asynchronous function and access it outside of that function's scope? I am working on a project where I need to randomize values in an array, so that I can assign images randomly to different div eleme ...

Utilizing Three.js Texture with shaderMaterial

I'm encountering an issue where I can't seem to load a texture onto my shader material, resulting in just black dots appearing. Here's the code snippet from my shader.js: THREE.ShaderLib['cloud'] = { uniforms: { textu ...

Nuxt has the ability to display the object itself, however, it cannot render its

I am using a directus API to fetch data, which is returned in an array of objects. I can render the array or an object from it, but not when trying to access a property of the object <template> <div class="grid grid-cols-2 gap-6 mt-6&quo ...

What is the best way to integrate a notification system using jQuery?

I am looking to create a notification area that will refresh whenever a new message is sent using jQuery or Ajax (my database is stored in a soap server). I want to make a soap call every few seconds to achieve this, but I'm not sure how to go about i ...

Tips for correctly identifying and sending the form name and submit button name when using AJAX for form submission

I need a concise solution to include the form name and submit button name along with the form input fields when sending data. I have attempted to use the form.serializeArray() method, but it only retrieves the input field names in the post data. Is there a ...

Using three.js to set the HTML background color as clearColor

How can I set the HTML background as clearColor using three.js? Here is the code snippet for three.js: // Setting up the environment var vWebGL = new WEBGL(); var scene = new THREE.Scene(); var camera = new THREE.PerspectiveCamera(75, window.innerWidth / ...

Issue detected in FullCalendar: date.getFullYear is not functioning as expected

I am working on adding a line of content to each cell in my calendar, specifically displaying the date in Hebrew next to the regular date number. Currently, I am testing with the standard sample calendar. The code snippet I am using is as follows: dayRe ...

What's causing Angular to not display my CSS properly?

I am encountering an issue with the angular2-seed application. It seems unable to render my css when I place it in the index.html. index.html <!DOCTYPE html> <html lang="en"> <head> <base href="<%= APP_BASE %>"> < ...

What is the process for creating a clickable file upload in Angular?

Currently, I am utilizing the instructions found in this guide to implement a file upload feature in my project. The code provided works perfectly: <input type="file" class="file-input (change)="onFileSelected($event)" #fileUplo ...

Trigger a notification from one webpage to another (PHP, JavaScript, HTML)

I'm currently working on a website that consists of both a receptionist page and a user page with multiple logins. The receptionist page displays a table listing all logged-in users, including their status (either ready or busy). This table is refresh ...

Looking for a prerequisite for running this script?

Seeking assistance from a skilled Javascript expert. I specialize in template development and utilize a specific script to display my footer link in all the free templates I create. If someone attempts to remove the footer link, their site will be redirec ...

Prevent PHP from redirecting during an HTML file upload

Is there a way to prevent the page from redirecting to the upload php file when the upload button is clicked? I'm looking for a solution within the code below. <form id="myForm" action="http://example/DB_1/AccessWeb/file_upload.php" method="post ...

Iterating Through Array with Node JS Before Adding a New Property

There is a JSON input with data connected to a secondary model called Users. To process this, I need to iterate through listingData.Agents to extract the index ID and then use this ID to find the corresponding user. The challenge here is that due to asynch ...

Exploring the capabilities of Typescript arrays by implementing a forEach loop in conjunction with the

I possess an array: set Array ( [0] => Array ( [name0] => J [name1] => L [name2] => C ) [1] => Array ( [data0] => 3,1,3 [data1] => 5,3 ...

CSS - Issue with dropdown sub-menu alignment despite using absolute positioning in relation to parent button

Title fairly explains it all. I'm having trouble getting my dropdown submenus to align perfectly with the bottom of the parent list item element. The list item has a relative position, while the submenu has an absolute position. I've attempted ...

Is it possible to send fetch requests to dynamic endpoints, such as remote URLs that don't have CORS enabled? Can the http-proxy-middleware library handle using variables in endpoint targets?

Using the fetch('htp://list-of-servers') command, a list of URLs is retrieved: test1.example.com test3.example.com test5.example.com The next step involves executing a fetch() function on each of these URLs: fetch('test1.example.com' ...