Tips for utilizing jQuery to identify an image that is being hovered on?

Concept

My goal is to create an effect where a user hovers over an image and a transparent overlay div appears on top of it. This overlay div starts with a height of 0px and should increase to half of the image height upon hover.

The hover functionality is working, but I suspect there is an issue with this line:

Update

After debugging and finding that the curHeight variable was 'undefined', I believe the problem lies in this line of code:

var curHeight = landingImg.clientHeight;

Here's the HTML structure:

<div id="landing-images">
    <div class="leftLanding">
        <div class="imageCover">
        </div>
        <img class="landingImage" src="assets/landingIMG1.png">
    </div>
    <div class="rightLanding">
        <div class="imageCover">
        </div>
        <img class="landingImage" src="assets/landingIMG1.png">
    </div>
</div>

And the JavaScript code:

$(".landingImage").hover(function () {
        console.log("hover works");
        var landingImg = $(this);
        var curHeight = landingImg.clientHeight;
        $(this).closest('.imageCover').css("height", curHeight / 2);
    }, function () {
        $(this).closest('.imageCover').css("height", "0px");
    });

Answer №1

To display the image properly, it is recommended to use the .siblings() method instead. Additionally, ensure that you include the width property in the div for it to be visible. You can utilize the .height() and .width() functions to retrieve the height and width of the image.

$(".landingImage").hover(function () {

        var landingImg = $(this);
        var curHeight = landingImg.height();
        var curWidth = landingImg.width();
        $(this).siblings('.imageCover').css("height", curHeight / 2);
        $(this).siblings('.imageCover').css("width", curWidth);
    }, function () {
        $(this).siblings('.imageCover').css("height", "0px");
        $(this).siblings('.imageCover').css("width",  "0px");
    });
.leftLanding,
.rightLanding {
  position: relative;
}

.imageCover {
  background: green;
  position: absolute;
  top: 0;
  z-index: 111;
  opacity:.5;

}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="landing-images">
  <div class="leftLanding">
    <div class="imageCover">
    </div>
    <img class="landingImage" src="https://www.w3schools.com/css/img_fjords.jpg">
  </div>
  <div class="rightLanding">
    <div class="imageCover">
    </div>
    <img class="landingImage" src="https://www.w3schools.com/css/img_fjords.jpg">
  </div>
</div>

Answer №2

.clientHeight represents a property within the DOM.

Convert

let currentHeight = landingImg.clientHeight;

Into

let currentHeight = landingImg.height();

Alternatively

let currentHeight = this.clientHeight;

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

What is the best way to refresh the user interface while executing a lengthy operation in AJAX/Javascript?

With a need to call multiple processes in series using synchronous AJAX calls, I aim to display the status of each long-running process upon completion before proceeding to the next. Below is an excerpt from the code that illustrates this concept: var co ...

What is the best way to eliminate a vertical line from an HTML table?

I am looking to remove specific vertical lines from an HTML table. There are only 3 vertical lines in total, and I want to remove the first and third lines. Below is my code: <html> <head> <style type="text/css"> .table1{ background: ...

The scaling transformation is not accurate for uneven pixel widths

I'm attempting to resize a div while keeping the inner element in the same position and at the same size. To achieve this, I am using transform: scale(value) on the wrapper and transform: scale(1/value) on the inside div. The issue arises when the in ...

Generate clickable links on a web page with PHP and a form

Every week I find myself tediously creating links by manually copying and pasting. It's starting to feel like a crazy process, and I'm sure there must be a faster way. A123456 B34567 d928333 s121233 I need these numbers to be transformed into h ...

Leverage the greater than operator within an AngularJS controller

This is the data stored in my controller: $scope.data = [{ "F": "1,26,000" }]; $scope.data2 = [{ "F": "26,000" }]; Now I want to implement an if-else condition using this data: if (Number($scope.d ...

What steps can be taken to retrieve data from a database table using JavaScript?

I am encountering a very peculiar issue. The values that I need are visible when I receive them as a message from the server-web console. However, when I try to retrieve them using a for loop, I encounter an error 05-22 18:58:23.203: I/Web Console(29392): ...

Preventing form submission with JavaScript by implementing multiple validation checks

Preventing a form from submitting when validation returns false is possible. Here's an example: <form name="registration" action="registration.php" onsubmit="return validate()"> <!-- some inputs like: --> <input type="text" id="us ...

Manipulating viewport settings to simulate smaller screens on a desktop device

I am working with a parent container that contains Bootstrap div.row elements holding div.col-... child elements. I am using jQuery to adjust the width and height of the container dynamically to replicate mobile device sizes for users to preview different ...

Looking for guidance on JavaScript - Implementing a different font family for each div element

I need help with customizing the font family for each individual post on my website. Currently, I am able to assign a cursive font to all posts within a class, but I would like each post to have its own unique font. Since I am doing this on load, I am fa ...

What are some ways to optimize Ajax requests for improved speed when multiple identical requests are made on a single webpage?

When the webpage is loaded, a block is dynamically created using an Ajax call to retrieve data from another page. This structure is then populated and added to a specific DOM element. However, multiple Ajax calls during page loads are causing delays. Is ...

Leveraging jQuery within a dynamically loaded div

I am attempting to implement some jQuery on a page that is loaded into a div using the .load() function. The PHP code loaded into the div contains a hidden section that slides out when a link is clicked. However, I am facing an issue where the div slides b ...

Steps to extract key and value from a collection in Firebase database

In my Firebase database, I have a specific structure that I need to retrieve and display using ngFor in my view. However, I also need access to the unique key generated by Firebase when using the push method for each object. https://i.sstatic.net/nR2nK.pn ...

Is there a way to streamline this function call that appears to be redundantly repeating the same actions?

I have developed a function to search for blog posts, prioritizing titles over excerpts and excerpts over content when added to the containsQuery array. While the code seems to be working well, I have noticed that there is a lot of redundant code. How can ...

The pop-up window is currently inactive

Utilizing the following example, I successfully created a modal window: jsfiddle The modal window allows me to display data from a table. Here is a snippet of my code: <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bulma/0.7.1/c ...

Ajax is able to fetch the URL without any issues, but the page is not being updated as expected. Instead,

I am currently working on implementing next/prev buttons using JavaScript, and have utilized a DynamicPage script for testing purposes. The only modification I made was to the beginning of the URL variable in pagenumber.js, although it essentially delivers ...

Updating the content of a window without the need to refresh the page using JavaScript

Is there a way to navigate back to the previous window in chat_user without refreshing the entire page when the back button is clicked? Below is the code I have tried: <a href="" onclick="window.history.go(-1); return false;">back</a> ...

Extracting individual elements from an array with Node.js or JavaScript

let array1= [ "home/work/data.jpg", "home/work/abc.jpg", "home/work/doc/animal.pdf", "home/work/doc/fish_pdf.pdf" ]; array1= array1.map((data)=>{ return data.slice(2,data.length).join("/"); }); console.log(array1); i am trying to modify my array by re ...

How come JavaScript's history.back() method does not display form values?

I have been developing an HTML form that submits values to a PHP script. When encountering errors, I currently display the error message along with a link containing javascript:history.back(). In Chrome, the form reopens with all values retained from the ...

wrap <td> data in a link with vue depending on certain conditions

I'm trying to customize the display of a particular table cell td. I want to show the data in a link if a certain condition is met, and if not, just show the data as text. However, I'm encountering some difficulties in implementing this. I have ...

How can I effectively set up and utilize distinct npm modules on my local environment?

A React Native component I have created lives in a separate folder with its own package.json file, and now I want to use it in another project. The component named MyComponent is located in Workspace/MyComponent and has specific dependencies listed in its ...