Prevent the hover() effect from affecting all div elements at once

I am aiming to achieve a function where hovering over a div with the "rectangle" class will display another div with the "description" class. Initially, the description div will have a display value of "none", but upon hovering, it should become visible.

var $projectOneHtml = $(".hTML-1")
var $projectTwoHtml = $(".hTML-2")
var $projectThreeHtml = $(".hTML-3")

function showDescription(x) {
  $(x).hover(function() {
    $(".description").show();
    $(this).addClass("hover");
  }, function() {
    $(".description").hide();
    $(this).removeClass("hover");
  })
};

showDescription($projectOneHtml);
showDescription($projectTwoHtml);
showDescription($projectThreeHtml);
.description {
  background-color: white;
  border: 1px solid white;
  width: 354px;
  height: 300px;
  text-align: center;
  color: black;
  font-size: 18px;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="projects">
  <div class="rectangle hTML-1">
    <img src="Projects/card.jpg" width="354px" height="180px">
    <div class="description">
      <p>A simple business card was created by HTML and CSS.</p>
    </div>
  </div>

  <div class="rectangle hTML-2">
    <img src="Projects/clock.jpg" width="354px" height="180px">
    <div class="description">
      <p>A simple clock design created using HTML and CSS.</p>
    </div>
  </div>

  <div class="rectangle hTML-3">
    <img src="Projects/canvas.jpg" width="354px" height="180px">
    <div class="description">
      <p>An artistic canvas made with HTML and CSS.</p>
    </div>
  </div>
</div>

The issue is: when I hover, all three divs are affected simultaneously. What I want is for only the specific description div to be displayed when hovering over its corresponding rectangle div. I hope this clarifies things. Thank you for your time.

Answer №1

The problem arises from selecting every .description element in the DOM when the mouseenter/mouseleave events are triggered. To resolve this issue, use find() starting from the event-triggering element to only impact its children.

It's important to highlight that incremental class names have been removed. This practice goes against the purpose of classes, which is meant to group elements based on common behavior.

$('.rectangle').hover(function() {
  $(this).addClass('hover').find(".description").show();
}, function() {
  $(this).removeClass("hover").find('.description').hide();
});
.description {
  background-color: white;
  border: 1px solid white;
  width: 354px;
  height: 300px;
  text-align: center;
  color: black;
  font-size: 18px;
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="projects">
  <div class="rectangle">
    <img src="Projects/card.jpg" width="354px" height="180px">
    <div class="description">
      <p>A simple business card was created by HTML and CSS.</p>
    </div>
  </div>

  <div class="rectangle">
    <img src="Projects/clock.jpg" width="354px" height="180px">
    <div class="description">
      <p>A simple business card was created by HTML and CSS.</p>
    </div>
  </div>

  <div class="rectangle">
    <img src="Projects/canvas.jpg" width="354px" height="180px">
    <div class="description">
      <p>A simple business card was created by HTML and CSS.</p>
    </div>
  </div>
</div>

In general, it's more effective to implement this kind of functionality using CSS alone since it offers better performance compared to JavaScript. You can try the following alternative approach:

.description {
  background-color: white;
  border: 1px solid white;
  width: 354px;
  height: 300px;
  text-align: center;
  color: black;
  font-size: 18px;
  display: none;
}

.rectangle:hover .description {
  display: block;
}
<div class="projects">
  <div class="rectangle">
    <img src="Projects/card.jpg" width="354px" height="180px">
    <div class="description">
      <p>A simple business card was created by HTML and CSS.</p>
    </div>
  </div>

  <div class="rectangle">
    <img src="Projects/clock.jpg" width="354px" height="180px">
    <div class="description">
      <p>A simple business card was created by HTML and CSS.</p>
    </div>
  </div>

  <div class="rectangle">
    <img src="Projects/canvas.jpg" width="354px" height="180px">
    <div class="description">
      <p>A simple business card was created by HTML and CSS.</p>
    </div>
  </div>
</div>

Answer №2

Personally, I believe in utilizing a CSS-only method for this instead of resorting to using JavaScript.

In this scenario, the following CSS code will ensure that the .description is only visible when its parent element is being hovered over:

div.rectangle:hover > .description {
  display: block;
}

You can observe this functionality in action in the snippet below, which does not rely on JavaScript:

.description {
  background-color: white;
  border: 1px solid white;
  width: 354px;
  height: 300px;
  text-align: center;
  color: black;
  font-size: 18px;
  display: none;
}

div.rectangle:hover > .description {
  display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="projects">
  <div class="rectangle hTML-1">
    <img src="//via.placeholder.com/354x180" width="354px" height="180px">
    <div class="description">
      <p>A simple business card was created by HTML and CSS.</p>
    </div>
  </div>

  <div class="rectangle hTML-2">
    <img src="//via.placeholder.com/354x180" width="354px" height="180px">
    <div class="description">
      <p>A simple business card was created by HTML and CSS.</p>
    </div>
  </div>

  <div class="rectangle hTML-3">
    <img src="//via.placeholder.com/354x180" width="354px" height="180px">
    <div class="description">
      <p>A simple business card was created by HTML and CSS.</p>
    </div>
  </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

Facebook pages and tabs utilize the [fbjs] JavaScript library

I am struggling to implement tabbing functionality on a Facebook application (business) tabs. Despite having some basic HTML and JS [fbjs], the code I have doesn't seem to be working. I can't figure out what is wrong. <div id="foo">foo di ...

What steps can I take to optimize my code and eliminate any redundancies?

In a current project, I need to make calls to three different endpoints. The functions handling these requests are identical except for the URLs being called. Below is an example of the code: const handleSubmitRequest = (e, next, endpoint, requestData) =&g ...

Eliminating fillers dashes from a text

Imagine having a string filled with soft hyphens like the one below: T-h-i-s- -i-s- -a- -t-e-s-t-.- The goal is to eliminate these soft hyphens and get back the clean string: This is a test. Attempting this task in JavaScript, here's how far I&apo ...

Streamline the process of creating and renaming directories within an Express.js application

My goal is to set up a basic Node.js Express website, and I'm executing the following commands: cd node npm install pug express express project_name cd project_name && npm install npm start After running this, the /public folder is being cre ...

Tips for minimizing the size of this script

I am new to using Jquery and Javascript, but I have managed to create a script that communicates with a php controller in symfony2. My query is, how can I shorten the script length? Is there a more efficient way to solve the logic instead of using the swi ...

Which language should I focus on mastering in order to create a script for my Epson receipt printer? (Check out the manual for reference)

Printer Model: TM-T88V User Manual: Receipt-marker Web template for the printer: (Provided by Epson) I'm completely new to computer languages and have been trying to understand how to print receipts. I've researched XML, HTML, CSS, and Jav ...

How can we detect if the pressing of an "Enter" key was triggered by an Angular Material autocomplete feature?

Currently, I have incorporated an Angular Material Autocomplete feature into my search bar. When a user types in their query and presses the Enter key, the search is executed as expected. Nevertheless, if the user decides to select one of the autocomplete ...

Create a specialized jQuery validation method for asynchronous validation

Is there a way to create a custom method using ajax for the jQuery Validate plugin? I've tried the following approach, but the validator keeps returning invalid every time. jQuery.validator.addMethod('customValidator', function (value, ...

Using JavaScript to implement responsive design through media queries

The code seems to be having some issues as it only works when I reload the page. I am looking to display certain code if "size < 700" and other code if "size > 699". I also tried this code from here: <script> function myFunction(x) { if ( ...

The combination of Superscrollorama and responsive design results in a lack of smooth flow

Looking to implement Superscrollorama animations for arrows on a specific website: The site is designed to be responsive across various sizes - 960+, 768, 480, and 320. Media queries are utilized to trigger the different layouts. While the arrows animate ...

Error encountered when downgrading a component from Angular v5 or v4 to AngularJS due to an injector issue

I have successfully created a basic angular5 component called HelloComponent: var HelloComponent = function () { }; HelloComponent.annotations = [ new ng.core.Component({ selector: 'hello-world', template: 'Hello World!' } ...

Organizing Vue.js components into separate files for a cleaner view model architecture

Having smooth functionality in a single file, I encountered difficulties when attempting to break up the code into multiple files and bundle it in a .vue file. Below is the final .vue file for simplicity. Here is the HTML file: <!DOCTYPE html> < ...

Design a div in the shape of a trapezium with clipped overflow

Is there a way to create a trapezium using CSS/Html/Canvas? I have attempted to do so, but my current method is messy and not practical. div { width:0; margin-left:-1000px; height:100px; border-right:1000px solid lightblue; border-top:60px solid tra ...

Problem with reordering rows in a PHP DataTable

While attempting to retrieve data from a database table and display it in a DataTable, I encountered the following error: DataTables warning: table id=example - Invalid JSON response. To learn more about this error, refer to http://datatables.net/tn/1 ...

Extension for Chrome - Personalized pop-up notification when page loads

I am looking to create a custom alert box that triggers on page load instead of the default one, which I find unattractive and possibly irritating for users. alert('hello'); My current approach involves the following code: manifesto.js "cont ...

Utilizing conditional statements within the array.forEach method to select specific sub-objects within an array of objects

Need help troubleshooting an if statement inside a function that is called by a forEach array loop. My array contains objects, with each object structured like this: arrofobj = [ {"thing_id":"1a", "val": 1, "Type": "Switch","ValType":{"0":"Open","1":" ...

The integration of VueJS with Axios and the Google Maps API

Currently following [this][1] guide to develop a Google Map and now I am looking to execute a GET request with Axios: axios.get("http://localhost:8080/mapjson").then(function(response) { }) in order to integrate the information from my JSON file into the ...

Ensure that the divs are properly aligned with the paragraphs

I received assistance previously, and I am seeking additional help in maintaining the position or adjusting the size of elements to fit different window viewport sizes such as tablets, mobile devices, or varying monitor sizes while keeping the appearance c ...

Dynamically adjust the gage value

Currently, I am working on a fitness application that involves showcasing BMI data using a gauge. However, I am struggling to figure out how to dynamically change the value of the gauge. In addition, when trying to implement the gauge script on button cl ...

Avoiding Rejected Promise: Warning for Error [ERR_HTTP_HEADERS_SENT] due to Issue with setInterval and Axios.post Error Management

I attempted to address this warning by researching online. Unfortunately, I couldn't find a solution, so I am reaching out with this question. The current warning that I am encountering is: (node:39452) UnhandledPromiseRejectionWarning: Error [ERR_H ...