Is there a way to get imagemap-style behavior in text?

Go To StackoverFlow.com

0

Remember imagemaps? They were all over the place in the 90s. A webpage would have an image on it, and when you clicked on it, it could take some action based on not just the image, but the exact pixel that you clicked.

Now, let's say that I've got some text in a div, rendered in a monospaced font, arranged as a 2D grid. Is there any way to put some Javascript on the div so that if I click on any character in that grid, it'll trigger a script and give it the index of the character I clicked on?

I know I could brute-force this by surrounding every single character in the grid with its own customized <a> tag, but is there any simpler way to do it?

2012-04-04 23:35
by Mason Wheeler


1

Here's a jsfiddle that proves the concept and seems to work. Each click will log to the console the matrix index of the letter clicked. (it's 0-based and column, row)

  • Put your text into a monospaced grid
  • attach a handler to the onClick of the containing element
  • Compute the dimensions of a single letter (such as "m") using a hidden element with just 1 letter
  • divide event.clientX and event.clientY by the dimensions of a single letter to get the coordinates of your clicked letter within your text

See also calculate text width with javascript.

2012-04-04 23:49
by Peter Lyons
That's interesting, but it's got some accuracy issues. From clicking around the letter J, I got all sorts of responses between (2,1) and (3,2). It's a good first start, though.. - Mason Wheeler 2012-04-05 00:29
Yeah, it's just a concept. I'm sure it can be made to work consistently though - Peter Lyons 2012-04-05 00:33
It gets a lot better if I use Math.floor instead of Math.round - Mason Wheeler 2012-04-05 02:56
Ads