When text is mistakenly displayed over an image instead of only appearing on hover

My goal is to implement a jQuery effect that displays text over an image when the user hovers over it. However, I've encountered some issues while modifying the code.

  1. Changing ".img" on line 3 in the jQuery to "img" results in the code working correctly but triggers the hover effect on a different image.

  2. If I remove the semicolon after "opacity: 0.75;" on line 4 in the jQuery, the code works temporarily, but any further interactions with the page cause the effect to malfunction.

I apologize for the lengthy code.

Here is the JSFiddle link to see the code in action: https://jsfiddle.net/9dsL2jyL/3/

Here's my code:

HTML

<div class="workInfo">
    <!-- Nav bar icon -->
    <img src="images/icons/navbar.png" id="hamburger" alt="Navigation Menu" onclick="openNav()">
    ... (Remaining HTML code here)
</code></pre>

<p>CSS</p>

<pre><code>.sidenav {
/* CSS styling here */
}

/* More CSS styles below */

.workDisplay img {
/* Additional CSS provided here */
}

jQuery

/* JavaScript code starts here */
$(window).load(function(){
$(".container").hover(function() {
    // Code for fade effect
    $(this).find(".fadeTop").fadeOut(300);
}, function() {
    // Reverses the fade effect
    $(this).find(".fadeTop").fadeIn(300);
});
})

// Hover effect implementation
$(document).ready(function() {
$('.text').hide();
    $('.img').animate({
        opacity: 0.75
    });

    $('.img').hover(function() {
        // Hover animation logic goes here
        $(this).stop().animate({opacity:.4},200);
        $('.text').fadeIn();

    }, function() {
        // Mouse out animation logic
        $(this).stop().animate({opacity:1},500)
        $('.text').fadeOut();
    });

Answer №1

When working with JQuery, you have the ability to select images using various methods. You can select images by image element like this: $("img"), or by class or id of an image like this: $(".imageclass") and $("#imageid") respectively.

If you want to target specific images for manipulation using JQuery's animate function, you can assign an additional class to those images. This way, the function will only impact the images that have been assigned that particular class. I hope this clarifies things for you.

Here is an example of how you can use the animate function on images with a specific class:

$(".imageclass").animate({
        opacity: 0.75;
    });

Answer №2

It's best to avoid using JavaScript
if the problem can be solved with CSS

html,body{
  height: 100%;
  margin: 0;
}

.box{
  width: 100%;
  height: 100%;
  font-size: 0;
}
.box-item{
  display: inline-block;
  width: 50%;
  height: 100%;
  font-size: 16px;
  position: relative;
}
.box-item:hover .box-item-text{
  opacity: 1;
  transform: translate(0, -50%) scale(1);
}
.box-item:hover .box-item-img{
  opacity: .8;
  -webkit-filter: blur(3px);
filter: blur(3px);
  // http://caniuse.com/#search=filter%3A%20blur
}
.box-item-text{
  font-size: 30px;
  color: white;
  text-align: center;
  position: absolute;
  z-index: 2;
  left: 0;
  right: 0;
  top: 50%;
  transform: translate(0, -50%) scale(.5);
  opacity: 0;
  transition: all 500ms linear;
}
.box-item-img{
  position: absolute;
  z-index: 1;
  left: 0;
  right: 0;
  bottom: 0;
  top: 0;
  // or background-size: cover !important;
  background-size: 100% 100% !important;
  -webkit-filter: blur(0px);
filter: blur(0px);
  transition: all 500ms linear; 
}
<div class="box">
  <div class="box-item">
    <div class="box-item-text">Lorem ipsum.</div>
    <div class="box-item-img" style="background: url(http://dummyimage.com/200x200/000/fff) 0 0 no-repeat;"></div>
  </div>
  <div class="box-item">
    <div class="box-item-text">Lorem ipsum.</div>
    <div class="box-item-img" style="background: url(http://dummyimage.com/200x200/000/fff) 0 0 no-repeat;"></div>
  </div>
</div>
            

Answer №3

If you come across this at a later time, I discovered that the issue was caused by the a tag enclosing the image in the workDisplay division. Once I removed this tag from my code, the hover effect started working perfectly.

Original HTML:

<div class="workDisplay">
    <a href="#">
        <div id="container">  
            <h2 class="text">
                A Play On Words
            </h2>
        </div>  
        <img class="img" src="images/cardphoto.jpg">
    </a>
</div>

Updated HTML:

<div class="workDisplay">
        <div id="container">  
            <h2 class="text">
                A Play On Words
            </h2>
        </div>  
        <img class="img" src="images/cardphoto.jpg">
</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 to easily toggle all checkboxes within a Vue.js checkbox group

I'm struggling with manipulating an Array of checkboxes that are grouped into parent and child elements. I need to automatically check all child checkboxes when the parent is checked, uncheck them if the parent is unchecked, and update their states in ...

There is no POST data present in the jquery ajax request

I have been attempting to send data back to a controller using ajax from a lightbox, but unfortunately, it is not working as expected. The issue arises when I select values from two populated select lists and click submit – an error message briefly appe ...

Google Chrome applying its unique style compositions

I recently started transitioning a website from HTML to Wordpress, and encountered an unexpected challenge with Google Chrome applying unfamiliar styles. Specifically, the issue lies with the positioning of the background image bg.gif. While Internet Explo ...

When using TouchableWithoutFeedback, I encountered the following error message: "Error: React.Children.only expected to receive a single React element child."

I am encountering the following issue: Error: React.Children.only expected to receive a single React element child. Whenever I incorporate the 'TouchableWithoutFeedback' component in my ReactNative project: return ( <TouchableWithoutFeed ...

What is the best way to transfer a variable to a Promise.all operation?

In the scenario presented, there is an attempt to pass the constant filter into the Promise.all function, but the method of passing it down is proving to be a challenge, resulting in it being undefined in the final line of code. What is the best way to pa ...

Responsive menu is failing to respond to the click event

I'm facing an issue with my responsive menu on mobile phones. It should display two buttons - one for the navigation bar and the other to toggle the side bar by removing the classes hidden-xs and hidden-sm. However, I am having trouble getting the btn ...

Tips on customizing the CSS responsiveness of your Bootstrap carousel

I have recently installed a Bootstrap theme on my Wordpress site and I am trying to make some CSS adjustments. One issue I am facing is with the carousel. Currently, when I resize the website or view it on a mobile device... The carousel maintains a lar ...

Can a TypeScript interface be exported as the result of a function?

Looking for a way to convert JSON schema to a Typescript interface in a more efficient manner. Here is an example of what the current method looks like: //Input var scriptSchema = { type: 'object', properties: { src: { type: &apo ...

Tips for developing an npm package that includes a demonstration application

When creating packages, I believe it's important to include a demo app. However, I'm unsure about the best way to organize the file structure for this purpose. My goal is to have one Github repository containing both my published NPM module and ...

Requesting data from a REST API using a nested query in a GET

After querying data from my MongoDB database, I am faced with the challenge of sending a GET request from the front end to meet this specific query. In my backend code, I retrieve the data using the following: const products = await Product.find({ &apo ...

What could be causing my search function to not recognize special characters?

It seems like there might be an issue with character encoding. My JavaScript search function is unable to identify specific strings that contain certain special characters such as parentheses, asterisks, and numbers. The JavaScript code I am using is quit ...

The order in which events are handled

Understanding Event Handling in Javascript and jQuery When an event (such as 'click') is bound to one function for the parent element and another handler function for a child DOM element, which of them gets called? If both are triggered, what is ...

How to locate the parent element's class using jQuery

I'm trying to assign a variable with the class of the parent div element. This is the snippet of HTML code: <li class="task" id="task_10"> <div class="10"> <a href="/tasks/10"> David Smith : Demo for Joe ...

Python's Selenium encountering a NoSuchElementException with the error message "./ancestor-or-self::form"

Trying to create a Python script that allows me to input my credentials and tweet text in the Python console. The script should then log in and post a tweet using Selenium. Everything works fine, except for the final click on the Tweet button which is caus ...

Utilize JavaScript and PHP to dynamically modify the contents of an HTML file

After not receiving a satisfactory answer to my question yesterday, I decided to find a solution. However, I am now facing an issue with the new program and unsure of the mistake. The program involves retrieving the contents of announcement.html and displ ...

The link function of an Angular directive is failing to execute

After following the ng-bbok tutorial, I encountered a strange issue where the code inside the link function was not being executed. It turned out that the problem stemmed from having an empty compile function before the link function in the directive defin ...

What is the solution to making text appear on the top rather than on the side?

Seeking a way to keep the text description above the textbox within a definition list, however currently the text appears to the left of the box. Here is the provided HTML structure: <dl> <dt> <label>Phone Number</label> &l ...

Adjust the Division's Width to be 20% of the Total Page Width Excluding Margins

https://i.sstatic.net/T0nKq.png I need to create a menu page with 5 equal columns, but I'm facing an issue with the layout. Here's my current CSS for the yellow divs: width:20%; height:100vh; background-color: yellow; display:inline-block; In ...

Personalized dropdown appearance

During my work on a select box, I discovered that custom styling is not possible. I attempted to use some plugins but did not find one that met my needs. I am seeking a dropdown menu with options in both black and gray, similar to this template but using ...

React with Typescript: The argument '{ [x: number]: any; }' is not compatible with the parameter type

After implementing the onChange method in my project using React, TypeScript, and Mobx, I encountered an error message stating: Argument of type '{ [x: number]: any; }' is not assignable to parameter of type Being new to TypeScript, I am unsure ...