Hi, I have an interesting JavaScript problem. I'm trying to create a right click menu for any word on a page. When the word is right clicked (or just clicked) I would like to highlight the word that was clicked on. To demonstrate I've attached some code that somewhat does this. It's not perfect though as it's a lot of processing on a big page - and it does not work correctly if there is HTML inside my span. Any other ideas on how to achieve this? I was also thinking I could capture the click event, determine the x,y position of the cursor. But still then - how do I locate the word on the page at coordinates x,y? You can do it if every word is it's own span (as below), but that is clumsy. To be clear, ideally I want you to click any word on the page and highlighting aside pop up an alert that says "you clicked on the word: hippopotamus"
Thanks for suggestions!
----------
<span id="rightclicks">
This is just a quick dirty example. It is not good because when lots of text is in
this span - it eats up user's CPU way too much. Also, it would not account for HTML
tags inside the text well. <a href="likethis.html">like this</a>
</span>
<script language="JavaScript">
function crclick(whichword) {
whichword.style.background
Color='#FF
FF00';
alert('you clicked on the word: "' + whichword.innerHTML + '"');
}
var rccon = document.getElementById('r
ightclicks
').innerHT
ML;
var rccon = rccon.replace(/\s+/g, ' ');
var rcconarray = rccon.split(' ');
var rightclicks2 = '';
for (i=0; i<rcconarray.length; i++) {
rightclicks2 = rightclicks2 + '<span id="w' + i + '" onclick="crclick(this);">'
+ rcconarray[i] + '</span> ';
}
document.getElementById('r
ightclicks
').innerHT
ML = rightclicks2;
</script>
Start Free Trial