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

How can I vertically align text in React-bootstrap Navbar Nav-items?

I have been struggling to find a solution to my problem without resorting to custom CSS classes. I'm wondering if it's possible to achieve what I need using only flex classes. Here is the code for a simple navbar component: <Navbar bg ...

Unveiling the Magic: Transforming Objects into HTML Attributes using AngularJS

I have been working on developing a highly dynamic ng directive that creates tables based on a given data array and configuration object. I am looking for a way to assign attributes dynamically based on an object within the scope. For example, if I have an ...

Above the search box in jQuery Datatable's search box, there is search text displayed

My datatable looks like this: var exTable1 = $("#exTable").DataTable({ "language": { "search": "Filter", "searchPlaceholder": "search", "loadingRecords": "", }, data: datasrc "dom": '<"top"lf>rt<"botto ...

Transform an angular1 javascript circular queue implementation for calculating rolling averages into typescript

I am currently in the process of migrating a project from Angular 1 to Angular 2. One of the key components is a chart that displays a moving average line, which requires the use of a circular queue with prototype methods like add, remove, and getAverage. ...

How to create ::after pseudo-element with identical width as its preceding sibling

My HTML code includes a <div> container with an <img> and an ::after pseudo-element. Check it out: <div class="container" data-caption="The caption should match the width of the image and wrap accordingly"> <img> </div> . ...

Arrangement of Columns in a Vertical Bootstrap Layout

When the xs layout displays as expected, how can I move the sidebar up to the navigation in order to eliminate the gap between them in the lg layout? <div class="row"> <div class="col-xs-12 col-lg-3 col-lg-push-9"> navigation & ...

What is the method for creating a checkbox in CSS that includes a minus symbol inside of it?

Can you create a checkbox with a minus "-" symbol inside using just html and css? I attempted to achieve this with JavaScript by using: document.getElementsByTagName("input")[0].indeterminate = true; However, the requirement is to accomplish this using ...

A method for highlighting duplicate rows in a DataTable by formatting them with the same color

I am currently utilizing the DataTable plugin to display rows in a table. I would like to highlight duplicate rows in the same color scheme. Can someone please assist me with this issue? In the example below, the entry for Black Winters is duplicated. I ai ...

Sorting Tables through the Power of Drag and Drop

While utilizing both the Jquery Tablesorter plugin and the Drag and Drop plugin together, everything seems to be functioning correctly. However, when attempting to use the serialize function of the tableDnD, an error message stating "empty string getElemen ...

Guide to establishing a connection to the Companies House API: Essential guidelines on setting up cURL headers and requisite API key specifications

I am attempting to establish a connection with the UK Companies House API, preferably using JavaScript. However, I am currently trying to set up this PHP version. How can I obtain access to the API using an API key? PHP: public function GetCompanyHouse( ...

Anti-virus programs are preventing long-standing AJAX connections

Hey there, I have come across something quite strange while developing a web application that relies on long-held HTTP connections using COMET to stream data between the server and the application. The issue I've encountered is that some anti-virus p ...

Retrieve input value in Angular 8 using only the element's ID

Can the value of an input be obtained in Angular 8 with TypeScript if only the element's id is known? ...

Ways to assign an identification attribute to HTML elements within innerHTML

Utilizing Ajax in conjunction with php $("#test1").click( .... function(data){ document.getElementById("test2").innerHTML=data; } ) php will return the data echo "<input type='text' id='test'>"; Seeking adv ...

Error encountered due to a circular reference in the dependency library

Whenever I attempt to run my application, I encounter the following error: > npm start Starting the development server... ts-loader: Using <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="42363b32273121302b323602716c776c71"& ...

Multer failing to generate file during request process

My current setup involves a router and multer middleware, but I'm facing an issue where the file requested is not being created. As a result, req.file always remains undefined. const multer = require('multer'); let storage = multe ...

What is the best way to change the value of a div using JavaScript?

i could really use some assistance, i am trying to ensure that only the selected template is shown on the screen, while all others are hidden. The expected outcome should be to replace the values of: <div class="city">City<span>,< ...

Tips for successfully retrieving a boolean value from an ASP.Net JavaScript AJAX request using a C# method

Query: Is there a way to call a C# function from JavaScript code on an .aspx webpage to get authentication results based on a username and password? Here is the JavaScript AJAX POST request I am currently using: $.ajax({ type: "POST", ...

Sending image to the server with the help of JavaScript

Curious if there is a method to upload an image to the server using javascript or jQuery and then save the image path/name into a database. I am working on a Windows platform server in asp.net 1.1, revamping a web page that is 10 years old. Unfortunately, ...

In jQuery, there seems to be an issue where the click event is not functioning properly on an element that has been

I am using jQuery to append items, but I am having trouble binding events to the appended items. My appending code looks like this: var item = '<div id="'+newInputId+'" class="col-md-9" style="padding-right: 0px; ...

Utilizing CSS to incorporate percentage points

Currently, I am facing a challenge in implementing a vertical line with percentage marks. It needs to be positioned relative to the percentage bar, just like how it appears in the screenshot below: https://i.stack.imgur.com/CNWUV.png I attempted a basic ...