Assign a CSS class to a DIV depending on the vertical position of the cursor

The website I am currently developing is located at

Within the site, there is a collection of project titles. When hovering over a project title, the featured image is displayed directly below it.

I would like to change the positioning of these images to display them above the title, but only if the Y position of the mouse cursor is below 50% of the browser window height.

To accomplish this, I believe that I will need to add an extra class to the span element for repositioning purposes, although I am unsure about the exact steps to implement this change.

Any assistance on this matter would be greatly appreciated :)

Answer №1

You already have experience with jquery, so you can use it to achieve what you need.

$(theTextElement).hover(function(e) {
  //Triggered on Mouse Over
  var y = e.pageY; //Get mouse Y position
  var windowY = $(window).height(); //Window height
  if((windowY/2)<y){
    $(theImageElement).addClass('viewTop'); //Toggle classes
    $(theImageElement).removeClass('viewBottom');
    $(theImageElement).show(); //Show the element
  }
}, function() {
    $(theImageElement).hide(); //Hide the element
});

This solution assumes CSS will handle positioning. You'll need additional logic for image selection and display.

If anything is unclear, feel free to ask for clarification.

Answer №2

If you want to track the movement of the mouse within a website, consider utilizing the "onmousemove" event. By comparing the Y position of the cursor with the height of the window, you can dynamically change the class attributes as needed.

Here's a helpful snippet for getting started:

document.onmousemove = function(event) {
  // Retrieve the X position of the cursor
  event.x;
  // Obtain the Y position of the cursor
  event.y;

  if(event.y < (window.innerHeight/2)) {
    // Implement changes to image classes here
  } else {
    // Handle alternative actions
  }
}

To optimize performance, it is recommended to place the event listener inside a Timeout function.

Answer №3

Assuming you prefer to maintain your current implementation where span elements are hidden until hovered over.

To determine each element's vertical position, you can use

elem.getBoundingClientRect().top

This will give you the distance from the top of the page.

You can find out the height of the window by using window.innerHeight.

It's a simple task to check if an element's top position is greater than half of the window's height

elem.getBoundingClientRect().top > window.innerHeight/2

If this condition is met, you could apply a class to the element to have it appear above the link title. However, there are multiple ways to achieve the same result.

Let's say you want to add a class to the spans so they appear above the title, you can either position them relatively and set a negative top css value, or you can utilize CSS3 transforms like this:

.above {
  transform: translate(0, -100%);
}

In this way, you won't need to worry about the span's height since CSS transforms use the target element's dimensions, not the parent container's.

Another important consideration is optimizing script load. You may want to check the position of the span element in the `onhover` event listener instead of checking all spans when the DOM is ready. Checking all spans at once can pause rendering and make the page seem unresponsive until the script loads.

Answer №4

If you're familiar with event.target, window.innerHeight, and event.clientY, a possible approach is using position:fixed and positioning based on the target's location.

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 determine and showcase the hours that have passed since the user's initial visit to the website?

Can someone provide guidance on how to finalize the hoursSinceFirstVisit() function implementation? Additionally, what content should be displayed on my HTML page? $(document).ready(function() { startTimer(); }); function startTimer() { setInte ...

The significance of API Input Validation and Steering Clear of Lengthy Conditional Statements

Currently, I am working on ensuring that my API functions correctly even in cases of bad or missing data. At the moment, I have an if statement that checks for any missing inputs. If an input is missing, it returns false, otherwise there is a large else b ...

Dynamic TypeScript class constructor argument typing determined by user input

I am working on creating a dynamic class that can adapt its argument properties based on a certain value. To illustrate this concept, let's consider a simple example: Imagine I have a class called Customizer, and depending on the value of the mode pr ...

A function designed to detect errors based on the parameters supplied as arguments

In order to ensure secure access to my restful API, I am looking to implement an authentication function called "access". I would like the function to have the following structure whenever a user interacts with the server: access(id , token ,function(err) ...

Issue with asmx Web Service causing failure to return JSON data when using FineUploader for file uploads

I acknowledge that there are numerous questions similar to mine regarding this issue, but none of them have provided a solution for me. I understand that web services inherently convert my objects into json as part of the framework. I manually set the requ ...

The State in the useEffect hook does not update instantly

After conducting some research, I discovered that useState operates asynchronously. However, I am still struggling to resolve my specific issue. My task involves fetching data from an API, but the state is only updated during the second render. Furthermore ...

Testing a close function in a modal using Karma-jasmine

Testing is new to me and I'm looking to test the close function and see if it renders properly in Angular. Here's the HTML structure: <div class="modal active" *ngIf="active" id="modal"> <div class=" ...

Here are steps to prevent swiping fancybox slides using mouse movement

Currently utilizing fancybox 3, I am looking to disable the swipe function for fancybox slides triggered by mouse movement. My preference is to only have the control buttons (next/prev) available. Is there a way to achieve this? Thank you. ...

Locate an element within the identical div that shares the same class

I want to dynamically add content inside a specific div by targeting its class name only after the user clicks on an element. Here is the layout structure: <div class="wrap"> <div class="divOne"> <div class="divOneItem">< ...

Using JavaScript to implement form authorization in ASP.NET Web API

I am looking to revamp a business application by utilizing asp.net web api as the service layer and implementing JavaScript to interact with the web api for retrieving and displaying data. While I have a good grasp on how all the scenarios will function s ...

Does element.click() in Protractor's Webdriver method return a promise, or is there a way for it to handle errors?

Is the element(by.css()).click() method returning a promise, or is there a way to catch and assert against any errors that may occur? In my scenario, I have a component that is not clickable, and I want to handle the error when this happens. I also want t ...

Cloud function for Firestore to recursively update a subcollection or collection group

I've been working on this cloud function: import pLimit from "p-limit"; const syncNotificationsAvatar = async ( userId: string, change: Change<DocumentSnapshot> ) => { if (!change.before.get("published") || !change.after.exists) { ...

Sharing controller methods in Angular.js is a key aspect of enhancing

In my current project, I originally used Knockout for the CMS functionality, but decided to switch to Angular because I preferred its features. One of the key sections in the CMS is dedicated to 'Users', featuring a table where headers can be cli ...

Utilizing JSDoc annotations for type safety in VSCode with ESLint configuration for TypeScript declarations import

Is there a way to configure VSCode to perform syntax checking on .eslintrc.js and provide autocomplete functionality? I have managed to set up a structure for a JavaScript configuration file with a custom syntax for my application, but the same approach do ...

Activate outline styling for Bootstrap radio buttons when clicked

I was in the midst of developing my bootstrap application. Every time I click on a radio button, there is a noticeable blue outline as shown here: https://i.sstatic.net/Uzm7b.png I attempted to address this issue using the following CSS code: .form-chec ...

jQuery uploadify encountered an error: Uncaught TypeError - It is unable to read the property 'queueData' as it is undefined

Once used seamlessly, but now facing a challenge: https://i.stack.imgur.com/YG7Xq.png All connections are aligned with the provided documentation $("#file_upload").uploadify({ 'method' : 'post', 'but ...

Insert text within the switch component using Material-UI

Looking to customize Material UI's Switch component with text inside? Check out the image below for an idea of what I'm going for. https://i.stack.imgur.com/KadRZ.png Take a look at my code snippet: import React from 'react'; import S ...

Arrange two div elements side by side so they remain adjacent even when you adjust the browser size

After years of success with my floated left and right divs, I am now facing a challenge with responsive design. No longer able to rely on fixed widths, I find that when the screen size decreases, the right div moves below the left one. I know that using f ...

Error unfound: [CLIENT_MISSING_INTENTS]: The Client requires valid intents to function properly

I've gone through multiple tutorials, but I keep encountering an uncaught TypeError. Despite following the suggested solutions, the error persists. I even tried implementing the "intent" solution, but it's prompting a change in "const client = ne ...

Changes made in the view of a VueJS application are not being reflected in Laravel when using

Embarking on my first journey with VueJS within a Laravel PHP framework has been quite the adventure. A new project is on the horizon, and I dove in headfirst by making various changes, such as adding new elements and altering titles. However, much to my d ...