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

Utilizing Angular 2+ to effectively manipulate the HTML Document Object Model with JavaScript in order to execute scripts

I'm facing an issue with inserting a script into my Angular project that has a specific format. <script type="text/javascript" src="https://s3.tradingview.com/external-embedding/embed-widget-events.js"> { "width": "510", "height": "600", "impo ...

What is the best approach to implementing a filter in Vue 2 that is also compatible with Vue 3?

Currently, I am utilizing Vue.js 2+ version and have implemented a date formatting filter to meet my needs. However, I recently found out that Vue 3 has removed the filter functionality in favor of using computed properties or methods. My dilemma now is ho ...

Steps for serializing HTML tags contained within a Form along with the Form itself

I am currently working on a form that allows users to input information for publication on the site. The form utilizes a combination of inline editing with contenteditable=true on editable HTML tags, as well as standard form inputs like selects and text fi ...

Executing an Ajax request to a document containing <script> elements

Recently, I developed a sample page that effectively mimics table layout pages but without relying on the traditional mobile-unfriendly table features. The structure of the page is as follows: <html> ... <body> <div type="page" ...

Keeping state between navigations in Ionic and AngularJS: A guide

In the process of developing my very first hybrid mobile application using Ionic and AngularJS, I have encountered a challenge that I am currently trying to resolve. The issue at hand involves maintaining the state of the graphical user interface between n ...

The output of jQuery('body').text() varies depending on the browser being used

Here is the setup of my HTML code: <html> <head> <title>Test</title> <script type="text/javascript" src="jQuery.js"></script> <script type="text/javascript"> function initialize() { var ...

Matching multiple divs with different ids in PHP using preg_match_all and regex

I have an HTML page structured like this: <!DOCTYPE html> <html> .... <body> <div class="list-news fl pt10 "> Blue </div> <div class="list-news fl pt1 ...

WebSocket connection established on port 8888, while the web server is running on port 80 - incompatible to merge the two services

Here is some node.js server-side code that involves watching a file and sending modifications to the browser: var app = require('http').createServer(handler) , io = require('socket.io').listen(app) , fs = require('fs') a ...

What is the best method for retrieving the character's ID from within an object?

Exploring my collection of movies, I discovered that each movie contains an array of characters. My goal is to display specific information about each character (such as their name and age) when clicked on, requiring me to obtain the id of each character. ...

What causes the Angular child component (navbar) to no longer refresh the view after a route change?

Hello everyone, I'm excited to ask my first question here. Currently, I am working on developing a social network using the MEAN stack and socket.io. One of the challenges I am facing is displaying the number of unread notifications and messages next ...

Having trouble getting getStaticProps to display JSX in Next.JS

I'm currently facing an issue with rendering basic data from a locally hosted Strapi API in my Next.js project. Although the data is successfully logged in the console, I am unable to map it into JSX. Below is the API get function: export async func ...

Implementing clickable table rows in React Router Link for seamless navigation

I'm relatively new to working with React. In my project, there is a Component called Content, which acts as a container for two other components - List and Profile. class Content extends Component{ <HashRouter> <Route exact path="/ ...

Utilizing the power of AWS Lambda in conjunction with moment JS to generate unique

My current time zone is GMT+8, and the AWS region I am using is Singapore (ap-southeast-1). I am facing an issue where there are discrepancies in date calculations between my local machine and when I deploy my code on AWS Lambda. My goal is to ensure that ...

Learn how to properly implement cookies in a fetch request within Nextjs

Here is a code snippet to consider: Index.getInitialProps = async function({req}) { const res = await fetch("http://localhost/api/tiles"); const json = await res.json(); } If the /api/tiles endpoint requires access to the uid cookie from the user, t ...

Creating a centered and beautifully styled picture with a specific maximum size using React

I recently completed the development of a new website, which can be viewed at Upon inspection of the website, it is evident that the photo is not centered and appears too large on mobile phones. Despite my efforts to align it using various methods outline ...

Include a <div> element to display the date in an HTML format, ensuring that the days and months

I am working on a project where I have a list of dates and I need to format them by adding div tags to separate the days, months, and years into different divisions. <div class="campaign">30/11/2016 - <a href="#" target="_blank">Dummy Text& ...

Guide on placing images in a grid using CSS

Exploring a new way to arrange images in grid style with a box underneath. Seeking advice on achieving this specific layout shown in an image. Current progress in positioning can be seen in this screenshot. Desired adjustments include aligning the far ri ...

How do I incorporate scrolling into Material-UI Tabs?

I am currently incorporating Material-ui Tablist into my AppBar component. However, I am facing an issue with the responsiveness of the tabs. When there are too many tabs, some of them become hidden on smaller screens. For more information on the componen ...

Express route fails to wait for Redis server response before moving on

How can I modify the code below to ensure that the res.json(...) command is not executed until all open calls to the Redis client.somecommand(..) have completed successfully? An issue occurs in the code where the client.hmset(uname, { ... } attempt to set ...

Activate Button upon Textbox/Combobox/RadDatePicker Modification through JavaScript

On my ASP.NET form, I have various input elements including textboxes, dropdowns, date pickers, and update buttons. My goal is to enable the update button whenever a user makes a change in any of these fields. To achieve this, I applied a specific CSS cla ...