Click event to reset the variable

The code snippet in Javascript below is designed to execute the function doSomethingWithSelectedText, which verifies if any text is currently selected by utilizing the function getSelectedObj.

The getSelectedObj function returns an object that contains information about the selected text.

An issue arises where the #text div updates with each text selection, and the #search div opens a new Google tab searching for the highlighted/selected text. However, the updating stops after the initial selection.

The probable cause could be that the addEventListener is implemented within the if() statement of the mouseup event, which prevents it from being updated further. How to address this dilemma remains uncertain.

index.html

<div id="popup">
    <div id ="text"></div>
    <div id="search" class="fa fa-search"></div>
    <div id="save" class="fa fa-file"></div>
</div>

styles.css

#popup{

display: none;
background-color: orange;
color: white;
position: absolute;
z-index: 1000;
width:100px;
height: 50px;
}

#search,#save {
display: inline-block;
padding: 15px;
font-size: 20px;
}

Answer №1

It is recommended to place the event handler outside of your function to prevent stacking up handlers that will all be executed on the next search click.

Below is an updated version of your code with the changes indicated by ***:

document.onmouseup = doSomethingWithSelectedText;
document.onkeyup = doSomethingWithSelectedText;

function getSelectedObj() {
    var selObj = {};
    selObj.text = '';
    if (typeof window.getSelection != "undefined") {
        // ***Additional safety measure to avoid runtime errors
        if (window.getSelection().rangeCount) {
            selObj.rect = window.getSelection().getRangeAt(0).getBoundingClientRect();
            selObj.text = window.getSelection().toString();
        }
    } else if (typeof document.selection != "undefined" && document.selection.type == "Text") {
        // This block is not used in newer versions of Chrome, Mozilla, and IE11
        selObj.text = document.selection.createRange().text;
    }
    return selObj;
}

// ***Variable for storing the search string
var searchStr = '';
// ***Using mouseup instead of click to prevent the document-level handler from being called
document.querySelector('#search').addEventListener('mouseup', function (e) {
    window.open('https://www.google.com/search?q=' + searchStr);
    return false; // ***Prevent bubbling up to the document
});

function doSomethingWithSelectedText(e) {
    var selectedObj = getSelectedObj();
    if (selectedObj.text) {
        console.log('text:' + selectedObj.text);
        document.querySelector('#popup').style.display = 'block';
        document.querySelector('#popup').style.top = e.clientY - 40;
        document.querySelector('#popup').style.left = e.clientX + 20;
        // ***Using textContent instead of innerHTML
        document.querySelector('#text').textContent = selectedObj.text;
        // ***Storing search string for future use
        searchStr = selectedObj.text;
    } else {
        document.querySelector('#popup').style.display = 'none';
    }
}

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

Retrieving multiple raw markdown files from GitHub using React JS

Currently, I am facing a challenge in fetching data from multiple raw .md files stored in different folders within a GitHub repository. Although I have successfully retrieved data from one file, my goal is to access all of them. The situation involves a G ...

Analyzing a CSV file and executing asynchronous operations on specific columns with the help of ajax requests

I possess a CSV file that contains placement links and target links formatted as follows: CSV Example [placement url],[target url] [placement url],[target url] [placement url],[target url] My objective is to parse the CSV file line by line using JavaScri ...

Looking to retrieve the value of an input element within an ng-select in Angular 6?

Currently, I am working on a project where I aim to develop a customized feature in ng-select. This feature will enable the text entered in ng-select to be appended to the binding item and included as part of the multiselect function. If you want to see a ...

Why does Internet Explorer throw a null pointer exception while Firefox does not?

My script loops through an array of HTML tag IDs, with some elements being empty. It works perfectly in Firefox but throws a null pointer or 'not an object' error in IE. if((storedVars.id) != ("")){selenium.browserbot.getCurrentWindow().document ...

Ways to align two divs side by side using CSS and HTML

Here is a question that needs solving: I have two elements that need to be displayed in one row at a specific ratio, with the same pattern repeating in subsequent rows. However, the content of the next row is appearing in the unused space of the previous r ...

placing a div inside another div

As I work on my website, I have created several panels with a repeating texture. To enhance the visual appeal of the site, I decided to add colored divs and adjust opacity for a tint effect instead of using separate images. The issue I'm facing is th ...

Challenges with Angular 4 service initialization

Having trouble with my authentication service. The constructor is being called 259 times when making an HTTP request, but only once when the call is removed. I am using a shared module to provide a unique instance of the service. Angular version: 4.4.4 C ...

Issues with the .change(function() JavaScript in Internet Explorer versions less than 9

I'm experiencing issues with this script in Internet Explorer versions below 9. Can someone please help me identify what is wrong with my script? Thank you. IE7 and IE8 are showing the following error: SCRIPT87: Invalid argument. Found ...

Legend click functionality works well in hiding the bars, but unfortunately, the data values in the charts.js are not being concealed as expected

When I click on the legend, the bar is hidden in the charts.js bar chart. However, the data value associated with the bar is not hidden. I have provided a link to the JS Fiddle code below: Check out the JS Fiddle here: https://jsfiddle.net/npyvw1L8/ var ...

Using Javascript to set up a callback that alerts when a script file is done loading with the attributes "async" and "defer"

My app is loading the platform.js file asynchronously with the attributes of async defer. <script src="https://apis.google.com/js/platform.js?onload=onLoadCallback" async defer> </script> I am looking for a callback function that will alert m ...

Ways to append each list item from one unordered list to the end of another based on their unique styles

I am in the process of making a website responsive and I am faced with the task of combining two different menus. In order to achieve this, I need to transfer all list items (li) from one unordered list (ul) to another. Provided below is a simplified vers ...

I encountered an error in my Rails 4 project where I got a NoMethodError stating "undefined method `id' for nil:NilClass" in my create.js

When I click a button, I'm attempting to display a partial. It seems like I am making an obvious mistake... and I suspect it's not related to the following code snippet: $('#modrequest').empty(); $('#modrequest').html("<%= ...

The session in Express.js is not retained across different domains

I am currently developing a third-party application that will be utilized across multiple domains. My main goal is to manage a session per user who uses the app, which led me to implement the express-session module for this purpose. However, I encountered ...

Navigate forward to the next available input in a grid by using the tab key

My goal is to improve form entry efficiency by using the tab key to focus on the next empty input field within a grid component. If an input field already has a value, it will be skipped. For example, if the cursor is in input field 2 and field 3 is filled ...

Is there a way to access comprehensive data pertaining to an ID through Ajax?

I need help with an Ajax call. Below is the code I currently have: $.ajax({ async: true, url: 'test/', type: 'POST', datatype: 'text json', data: { id: id, }, success: function(data) { // Retrieve the da ...

reversing an array does not have an effect

Whenever I attempt to reverse the order of my array using the reverse() function, the changes do not reflect in the view until I make a change to the file and save it. Items.js: import { useState } from "react"; const Items = (props) => { ...

What is the best way to split the children of a parent div into four distinct styling regions using the nth-child selector?

Imagine having a square parent container with 100 child elements of equal sizes, as illustrated below. How can you use the :nth-child selector to target and style the children in the top-left, bottom-left, top-right, and bottom-right corners separately? ...

The script is malfunctioning on Google Chrome

Below is a script that I have: EXAMPLE : <script> var ul = document.getElementById("foo2"); var items = ul.getElementsByTagName("li"); for (var i = 0; i < items.length; i=i+2) { // perform an action on items[i], which repr ...

Using Javascript's OnChange event to dynamically update data

Attempting to achieve a seemingly straightforward task, but encountering obstacles. The goal is to trigger a JavaScript onChange command and instantly update a radar chart when a numerical value in a form is altered. While the initial values are successful ...

Retrieve a div element using Ajax from the result of an If statement

I need to extract a specific div from the data returned by an if statement that is formatted as HTML, and then display it within another div. I have been attempting to achieve this using the code below, but so far it has not been successful... Here is my ...