Tips for retrieving the clicked word in JavaScript

Is it possible to retrieve the word that was right-clicked on along with its x, y coordinates? I attempted the following code:document.onclick=getTextOnClick;

function getTextOnClick(e)
{
    console.log(e);
    if (window.getSelection) {
        txt = window.getSelection();
            console.log(">>>"+txt);
    } else if (document.getSelection) {
        // FireFox 
        txt = document.getSelection();
            console.log(txt);
    } else if (document.selection) {
        // IE 6/7 
        txt = document.selection.createRange().text;
            console.log(txt);
    }
}

This code successfully captures selected text, but is there a way to achieve the same result when simply right-clicking or clicking on a specific word? The event object provides click coordinates - can these be modified to give coordinates of the clicked word instead? Any assistance would be greatly appreciated.

Answer №1

If your container includes only "simple" words, you can achieve this using just JavaScript:

window.onload = function() {
    var oDiv = document.getElementById("Container");
    var rawHTML = oDiv.innerHTML;
    var arrWords = rawHTML.split(" ");
    oDiv.innerHTML = "";
    for (var i = 0; i < arrWords.length; i++) {
        var curWord = arrWords[i];
        var curSpan = document.createElement("span");
        curSpan.innerHTML = curWord;
        if (i < (arrWords.length - 1))
            curSpan.innerHTML += " ";
        curSpan.onclick = WordClicked;
        curSpan.oncontextmenu = WordClicked;
        oDiv.appendChild(curSpan);
    }
};

function WordClicked() {
    var word = this.innerHTML;
    alert("You clicked: " + word);
    return false;
}

Check out the live test case - it works for both left and right clicks.

Answer №2

One suggestion is to enclose each word within a separate span tag. However, achieving consistent performance across all browsers may present challenges.

Answer №3

Why not give this a try?

Check out this text:

<div id="bar">Greetings! I am words on a screen, serving a mysterious purpose. Although unsure of my significance, I do offer notable phrases and other curious elements.</div>

Using jQuery:

$('#bar').contents().each(function(_, node) {
    var list = node.textContent.split(/\s/).map(function( word ) {
        return $('<span>', {
            text: word + ' ',
            click: function() {
                alert( $(this).text() );
            }
        }).get(0);
    });

    $('#bar').empty().append(list);
});

See it in action here: http://jsfiddle.net/mQpuC/

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

Setting up a new folder in the internal storage within a React Native Expo environment

In my React Native Expo project, I am utilizing two functions to store data in a JSON file and then save the file to internal storage. However, the code currently asks for permission to store inside a chosen folder, but does not create the "ProjectName" fo ...

Learn the technique of invoking a sub component's method from the parent component in Vue.js

I am looking to trigger a method in a sub component from the parent component in Vue.js in order to refresh certain parts of the sub component. Below is an example showcasing what I aim to achieve. Home.vue <template> <componentp></compo ...

The request for the URL (https://deno.land/std/encoding/csv.ts) could not be sent due to an operating system error with code 100

Encountering an issue with importing the stdlib files from deno.land to the local cache when running mod.ts. Error: error sending request for url (): error trying to connect: tcp connect error: An attempt was made to access a socket in a way forbidden by ...

Retrieving Value from Dynamic Content Using jQuery `.keypress()` and `.delegate()`

I have encountered an issue with my code that is unable to retrieve the value of a specific ID on the .keypress function after using .delegate. The ID and other contents are generated dynamically through an AJAX call. $(document).delegate('.edit_ ...

Is there a more efficient approach to extracting the border width using javascript?

I implemented the following code: const playGard = document.getElementsByClassName("playGard")[0]; const borderW = getComputedStyle(playGard,null).getPropertyValue('border-left-width').substr(0,2); The result I obtained was "10". Is there a m ...

Submitting Forms with XMLHttpRequest

I'm trying to utilize XMLHttpRequest in order to retrieve the response from a remote PHP file and showcase it on my webpage. The issue I'm facing is that the form's data isn't being submitted to the remote PHP page. Any suggestions on ...

If a user enters an incorrect path, the goal is to automatically redirect them to the homepage while displaying the correct URL in AngularJS

When the URL is manually edited, the webpage displays the same content with a different URL structure. For instance, http://www.example.com/# and http://www.example.com/#/abc both show identical content. I would like to implement a redirect for any edite ...

Decipher intricate JSON with JavaScript

After retrieving a JSON object from Mongo DB, I have this data structure. **JSON** { "_id" : ObjectId("5265347d144bed4968a9629c"), "name" : "ttt", "features" : { "t" : { "visual_feature" : "t", "type_feature" : ...

What scenarios call for the utilization of setScriptTimeout?

When using Selenium WebDriver, there is a method called setScriptTimeout(time, unit). The description of this method states that it Specifies the time allowed for an asynchronous script to finish executing before an error is thrown. If the timeout is set ...

Header and Footer Components in ReactJS

My goal is to design a unique Layout component that will display the Header and Footer. This way, I can later use the Layout like <Layout> ... </Layout> In order to achieve this, I have utilized Routing in both the Header and Footer. To imple ...

What's the best way to transform createHmac function from Node.js to C#?

Here's a snippet of code in Node.js: const crypto = require('crypto') const token = crypto.createHmac('sha1', 'value'+'secretValue').update('value').digest('hex'); I am trying to convert t ...

Dealing with errors such as "Failed to load chunk" can be resolved by implementing lazy-loading and code-splitting techniques

Our team is currently working on a Vue.js application using Vue CLI 3, Vue Router, and Webpack. The routes are lazy-loaded and the chunk file names include a hash for cache busting purposes. So far, everything has been running smoothly. However, we encoun ...

Display requested tab feature using jQuery upon page load

I am new to jquery and have been using this code for creating tabs: <script type="text/javascript" charset="utf-8> $(function () { var tabContainers = $('div.tabs > div'); tabContainers.hide().filter(':first&apo ...

Clicking on a button in HTML to open a JavaScript file

As a beginner in HTML and JavaScript, I am looking for a way to open a JavaScript file when the onclick event of a button in my HTML file is triggered. Can anyone provide me with guidance on how to achieve this? Thank you in advance. ...

The StreamingTextResponse feature is malfunctioning in the live environment

When I share my code, it's an API route in Next.js. In development mode, everything works as expected. However, in production, the response appears to be static instead of dynamic. It seems like only one part of the data is being sent. I'm puzzl ...

step-by-step guide for resolving issues with downloading files in node.js

I've been attempting to download files from my server using node.js with the res.download function from Express, but I keep getting an undefined error. The folder path is D:\program\web\java_script\Node\my_project\ketabk& ...

What is the best way to directly send a message from a panel to a page-mod's content script?

When working with a code snippet in a Firefox addon like the one below: var pagemod = PageMod({ include: ['*'], contentScriptFile: [data.url('content.js')] }); panel = require("sdk/panel").Panel({ width: 322, height: 427, ...

Utilize images stored locally in ReactJS

My path to the image is: ../src/assets/images/img_name.jpg" And my path to the file.js is: src/file_name.js If I include the following code in file.js: Import img_name from "../src/assets/images/img_name.jpg" Then reference the image pa ...

Ensuring Valid Submission: Utilizing Jquery for a Straightforward Form Submission with 'Alajax'

After searching for a straightforward JQuery plugin to streamline the process of submitting forms via Ajax, I stumbled upon Alajax. I found it quite useful as it seamlessly integrates into standard HTML forms and handles all the necessary tasks. However, I ...

What is the best way to trigger the download of an image file created by PHP to a user's computer?

My PHP code (upload.php) allows users to upload an image from index.html, resize it, add a watermark, and display it on the same page. Users can download the watermarked image by using the 'Save image as...' option. The resized image is saved in ...