Display a div when hovering over an image using jQuery

I've spent a good 30 minutes searching on Stack Overflow for a solution, but I haven't been able to find it yet. It's possible that I'm not sure what exactly to look for.

Essentially, I have a div that contains an image and some text. The objective is for the text to only appear on the image when I hover over it. The HTML and CSS structures are correct, but I am struggling with the JQuery hover function, particularly in terms of how to select the inner div (not just how to use the hover function itself).

What I aim to achieve is that when I hover over an image div (img-container), the corresponding text (hover-img) appears on top of the image.

Here is my code:

HTML

<div id="content" class="col-12">
  <!-- Image Gallery -->
  <div class="col-lg-4 col-md-6 col-xs-12 img-container">
    <img class="img-gal" src="#" />


    <div class="hover-img">
      <p class="img-text">Text on Hover</p>
    </div>
  </div>
</div

CSS

.img-container{
  float:left;
  margin: 0;
  padding: 0;
  cursor: pointer;
  position: relative;
}

.img-gal{
  width: 100%;
  height: auto;
  position: relative;
}

.hover-img{
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index:10;
  color: #fff;
  display: none;
}

.img-text{
  text-align: center;
  position: relative;
  top: 50%;
  font-weight: 300;
  font-size: 1em;
  letter-spacing: 2px;
}

JS

//Hover Image. Need to show the Text when hovering on an image
$('.img-container').hover(function(){
  //Stuck here. How to display the text? fadeIn()? But how?
},function(){
  //Still stuck. How to hide the text? fadeOut()? But how?
});

Thank you

Answer №1

You can easily accomplish this using only CSS:

.hover-img {
  display: none;
  position: absolute;
  top: 0;
}

.img-gal:hover ~ .hover-img, .hover-img:hover {
  display: block;
}
<div id="content" class="col-12">
  <!-- Image Gallery -->
  <div class="col-lg-4 col-md-6 col-xs-12 img-container">
    <img class="img-gal" src="https://www.gravatar.com/avatar/0104050baad43a135d1084a1b3ec35d4?s=32&d=identicon&r=PG&f=1" />


    <div class="hover-img">
      <p class="img-text">Text on Hover</p>
    </div>
  </div>
</div

Answer №2

Like others have mentioned, there is no need for jQuery in this case. You can achieve the desired effect using just html/css by manipulating the opacity and position of the text layer with css transitions.

Check out this fiddle for a working example.

CSS:

.gallery li {
  overflow: hidden;  
  background-size: 100% 100%;
  float: left;
  display: block;
  width: 200px;
  height: 200px;
  margin: 5px;
}

.gallery span {
  display: block;
  width: 100%;
  height: 100%;
  opacity: 0;
  transform: translateY(100%);
  transition: .3s linear all;
  text-align: center;
  color: #000;
  font-size: 15px;
  font-family: tahoma;
  background-color: rgba(255, 255, 255, .8);
  padding-top: 30px;
  box-sizing: border-box;
}

.gallery li:hover span {
  transform: translateY(0);
  opacity: 1;
}

HTML:

<ul class="gallery">
  <li style="background-image:url(https://cdn.pixabay.com/photo/2018/01/17/10/22/key-3087900__180.jpg)">
    <span>Style 1</span>
  </li>
    <li style="background-image:url(https://cdn.pixabay.com/photo/2018/02/16/02/03/pocket-watch-3156771__180.jpg">
    <span>Style 2</span>
  </li>
      <li style="background-image:url(https://cdn.pixabay.com/photo/2018/04/20/02/47/hong-kong-3334945__180.jpg)">
    <span>Style 2</span>
  </li>
<li style="background-image:url(https://cdn.pixabay.com/photo/2018/01/17/10/22/key-3087900__180.jpg)">
    <span>Style 1</span>
  </li>
    <li style="background-image:url(https://cdn.pixabay.com/photo/2018/02/16/02/03/pocket-watch-3156771__180.jpg">
    <span>Style 2</span>
  </li>
      <li style="background-image:url(https://cdn.pixabay.com/photo/2018/04/20/02/47/hong-kong-3334945__180.jpg)">
    <span>Style 2</span>
  </li>  
</ul>

Answer №3

To achieve this effect using only CSS, include the following line in your stylesheet:

.img-gal:hover + .hover-img {
    display:block;
}

If you prefer a smoother transition, add the following lines to the .hover-img class and remove display:none:

.hover-img {
    visibility: hidden;
    opacity: 0;
    transition: opacity 0.5s ease-in-out;
}

Then, apply the hover effect to an image like this:

.img-gal:hover + .hover-img {
    visibility: visible;
    opacity: 1;
}

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

I’m keen on utilizing JQuery with Node.js and EJS, but I’m encountering an issue where $ is not

I attempted to incorporate JQuery in my project by following these steps. Installed jquery using npm install Modified the package.json file Despite this, the functionality still does not work as intended. Below is a snippet of the .ejs page: <html& ...

Retrieve file using Ajax (kind of)

I have implemented an AJAX call in my GSP: $.ajax({ url: '${request.contextPath + '/Ticket/passAll'}', type: 'POST', data: data, success: function() { alert("Success"); } }); Below is a code snipp ...

Chrome-specific bug in DataTable sorting with jQuery - looking for workaround to fix the issue

Here is my code snippet: jQuery.fn.dataTableExt.oSort['num-asc'] = function(a,b) { var x = a.replace( /<.*?>/g, "" ); var y = b.replace( /<.*?>/g, "" ); x = parseFloat( x ); y = parseFloat( y ); return ((x < y ...

The Node.js EventEmitter encounters an error stating `listener must be a function` when the `typeof` operator indicates that the value is a function, hint

Dealing with an object that is being interacted with by multiple node.js modules has presented some challenges. My goal is to allow certain modules to add eventListeners to the object. In my codebase, I have an events file where event emitters are attach ...

Unable to show inline within web forms application utilizing bootstrap

I am currently modifying the account registration section of a new VS 2013 web application that uses bootstrap css for formatting. I am working on creating a form on a page and struggling to get one section to display inline instead of as a block element. ...

Accessing a local JSON data file via an AJAX call

function fetchColor() { var promise = $.Deferred(); $.ajax ({ url: 'ajax/color/Red.json', dataType: 'json', type: 'get', success: function(data){ promise.resolve(data); ...

Toggle the Bootstrap navbar class based on the current scroll position

I'm currently working on the development of a website that includes a feature where a static navbar transforms into a fixed navbar after scrolling down 500px. The transition from "navbar-static-top" to "navbar-fixed-top" is functioning properly. Howev ...

Is it possible to run concurrent PostgreSQL queries in NodeJS?

I'm unsure why, but the task is supposed to be run in parallel and should only take 2 seconds: const test = async () => { client.query("SELECT pg_sleep(2) FROM test", (err, result) => { console.log("DONE!"); }) client.query("SELECT pg ...

Creating a three-dimensional shape using a transparent image in Three.js

Hey there! I'm currently working on creating a 3D model that features the upper and lower sides as transparent images, while the other sides are a solid color (yellow in this case). var texture = new THREE.TextureLoader().load( 'img.png' ); ...

Using the `document.querySelector` method to target the `.mat-progress-bar-fill::after` element

Is there a way to dynamically adjust the fill value of an Angular Material Progress Bar? In CSS, I can achieve this with: ::ng-deep .mat-progress-bar-fill::after { background-color: red; } However, since the value needs to be dynamic, I am unable to do ...

Unveil Secret Divs with a Click

I am in search of a way to display a hidden div when I click on a specific div, similar to the expanding images feature in Google's image search results. I have made progress with my limited knowledge of javascript, as shown in this CodePen: http://co ...

Sporadic success with Ajax operations

The functionality of this ajax code seems to be intermittent. Can someone help me troubleshoot the issue? App.controller('sendemail', function (page) { $.ajax({ type: 'GET', url: 'http://sanjuwebworks.com/conte ...

Buffering ceases on the video

I am experiencing an issue with 4 videos and a preloader, which should hide once all the videos are fully buffered. <div id="preload"> <h1> Download... </h1> </div> <video preload="auto" class= ...

Using Conditions in AngularJS: Choosing Between Callbacks and Promises in a Service

I am currently faced with a specific scenario where I am uncertain whether to implement a callback or a promise. As someone who is relatively new to promises and just beginning to grasp their concept, I want to avoid falling into any potential anti pattern ...

Integrating Instagram photos onto a website

I came across this code on a forum, but unfortunately, it didn't work as expected for me. The photo didn't display, only the header appeared. Is there anyone who can assist me with this issue? <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 ...

What is the best way to display the entire background image in a jumbotron?

After some experimentation, I discovered that by increasing the amount of content I have, it displays the full background image. Is there a clean and efficient way to achieve this? <div class="jumbotron jumbotron-fluid" style="background: url('./a ...

What might be the reason for npm live-server to cease detecting file updates?

Everything was working perfectly on my system, but now I'm facing an issue. I have the live-server version 0.8.1 installed globally. npm install live-server -g However, when I start it, I no longer see the "Live reload enabled." message in the brow ...

Displaying a hand cursor on a bar chart when hovered over in c3.js

When using pie charts in c3js, a hand cursor (pointer) is displayed by default when hovering over a pie slice. I am looking to achieve the same behavior for each bar in a bar chart. How can this be done? I attempted the CSS below, but it resulted in the h ...

What are the implications of adding custom attributes to HTML elements?

Similar Questions: Custom attributes - Good or Bad? Non-Standard Attributes on HTML Tags. What are Your Thoughts? While working on a current learning project, I encountered the need to add an attribute that would store a numerical value. Initially ...

How can I extract information exclusively from child nodes with Jsoup?

Currently, I am facing an issue with extracting first-level <li> elements from a <ul> element. Even though I attempt to retrieve only the first-level <li> elements using Jsoup selector or getElementsByTag, the nested <li> elements w ...