In a block of a monospace text, is there a javascript snippet or JQuery plugin that gets coordinate (row & col of text, not pageX & pageY) of the character under mouse cursor and highlight the character?
+1
A:
Here's some code I hacked together to do it. It wraps every character in the <pre>
with a <span>
. The <span>
s use onmouseover
and onmouseout
to highlight the character and put the row and column in the <div>
below the <pre>
.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<style type="text/css">
#coordText {
font-family: "Courier New", Courier, monospace;
overflow: auto;
}
</style>
<script type="text/javascript" >
function showinfo(row, col) {
$('div#info').html("row " + row + ", col " + col);
$('#r' + row + 'c' + col).css('background-color', '#ddd');
}
function hideinfo(row, col) {
$('div#info').html('');
$('#r' + row + 'c' + col).css('background-color', '#fff');
}
$(document).ready(function() {
var text = $("#coordText").text();
var html = '';
var col = 1;
var row = 1;
for (var i=0; i<text.length; i++) {
if (text.charAt(i) == '\n' || text.charAt(i) == '\r') {
if (i > 0 && text.charAt(i-1) == '\r')
continue;
row++;
col = 1;
html += '<br />';
} else {
html += '<span id="r' + row + 'c' + col;
html += '" onmouseover="showinfo(' + row + ', ' + col;
html += ')" onmouseout="hideinfo(' + row + ', ' + col;
html += ')">' + text.charAt(i) + '</span>';
col++;
}
}
$("#coordText").html(html);
});
</script>
</head>
<body>
<pre id="coordText">Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Pellentesque imperdiet velit ut sem pulvinar pulvinar.
Sed sed molestie justo. Mauris blandit est sit amet lacus cursus et porta lorem gravida.
Nunc eget leo id diam faucibus lobortis non volutpat est. Fusce facilisis consectetur congue.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sodales lectus et ligula luctus sit amet ornare sem dignissim.
Nunc fringilla tempus leo in accumsan.
Cras facilisis quam non arcu mollis pretium.
In hac habitasse platea dictumst. Maecenas vitae turpis ante.
Cras lorem mauris, iaculis nec sollicitudin id, dapibus in nunc.</pre>
<div id="info"></div>
</body>
</html>
Rob
2009-08-10 20:23:47
-1 please format, shorten, explain
tharkun
2009-08-10 20:29:06
This solution is extremely slow for large block of text on my Firefox 3.5.
btw0
2009-08-11 05:59:50