Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS grid layout - how to work out which grid cell the mouse is in with javascript?

"css grid layout" = https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout

Does anyone know of a javascript way to work out what column / row the mouse is currently in?

I'm guessing something like this is a start for getting the what cell the mouse is in however this would only be useful for grids of equal sizes.

MouseGridColumn = round(mouseX / ( gridContainerWidth  / gridTotalColumnsNumber ) )
MouseGridRow    = round(mouseY / ( gridContainerHeight / gridTotalRowsNumber    ) )

Is there a way to do this with cells that aren't equal?


Update 1 - adding a codepen

Here is a codepen which shows 3 various percentage column widths (grid-template-columns: 25% 50% 25%;), 2 rows, a grid cell with no element with in it and an element that spans more than one row: http://codepen.io/anon/pen/NbeOXp


Update 2 - attempt at working out what grid cell the mouse is in.

Here I have added hidden elements to each cell in the grid to detect which cell the mouse is in. However it only returns "auto" for the current element it is in. It's also pretty clunky having to add extra hidden elements to the grid IMO.

http://codepen.io/anon/pen/gLZBZw Hint: use the mouse to hover over the grid.

like image 584
Jammer Avatar asked Dec 17 '16 13:12

Jammer


People also ask

How do you name grid areas in CSS?

We can name grid areas. A grid area is a rectangular area consisting of one or more grid cells. The area is defined by four grid lines marking out the start and end lines for columns and rows. We name areas of the grid using the grid-template-areas property.

What is grid in JavaScript?

JavaScript Grid, also known as the JavaScript DataGrid, is a feature-rich control for displaying data in a tabular format. Its wide range of functionalities includes data binding, editing, Excel-like filtering, custom sorting, aggregating rows, selection, and support for Excel, CSV, and PDF formats.

Is it safe to use CSS grids?

It is definitely safe to use.


1 Answers

Add event listener to the parent of the grid colums. Its called event delegation. You can use event.target in on hover event and inside for loop compare the ev.target.parent element==document.querySelect("#parentElement")[index] Post all ur code html code to write it exactly if you want.

like image 135
partizanos Avatar answered Sep 20 '22 05:09

partizanos