When scrolling, the selected text does not maintain its correct position

I'm looking to enable my users to search by selecting text. Once they select text, a new button will appear on the right side of the selected text giving them the option to search or not. However, when the user scrolls to the bottom of the page, the position of the search button is not correct. Here is the code snippet:

HTML:


<body ng-app="newsApp" ng-controller="NewsCtrl" ng-mouseup="showSelectedText($event)">  

     <!-- User search button -->
     <div ng-show="isUserSearch" ng-style="{ 'left' : leftPos, 'top': rightPos, 'display': displayState }" class="searchBtn">
        Search             
     </div>

     <!-- Main content -->
     <div>
       <!-- Main content -->
    </div>

</body>

CSS:


.searchBtn {
    position: absolute;
    padding: 4px 7px;
    background-color: #ff0;
    color: #ddd;
    z-index: 9999;
    border-radius: 5px;
    height: 27px;
    cursor: pointer;
 }

Javascript:


angular.module('newsApp', [])

   .controller('NewsCtrl', function ($scope) {

       $scope.leftPos = "-200px";
       $scope.rightPos = "-200px";
       $scope.displayState = "none !important";
       $scope.isUserSearch = false;

       $scope.selectedTextSearch = "";

       $scope.showSelectedText = function($event) {
          $scope.selectedText =  "";

          if (window.getSelection) {
             $scope.selectedText = window.getSelection().toString();
          } 
         else if (document.selection && document.selection.type != "Control") {
             $scope.selectedText = document.selection.createRange().text;
          }

          if($scope.selectedText.length > 0) {            
             $scope.leftPos = (+$event.clientX + 5) + 'px';   
             $scope.rightPos = (+$event.clientY - 15) + 'px';  
             $scope.isUserSearch = true;
          } else {
             $scope.isUserSearch = false;
          }
       };

   });

Plunker

What should be my next step?

Answer №1

Replace clientX with pageX

$scope.leftPos = (+$event.pageX + 5) + 'px';   
$scope.rightPos = ( +$event.pageY - 15 ) + 'px'; 

Check out this reference for more information.

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

An issue arises when attempting to utilize the 'push()' method to append a string to a JSON array

I am looking to append strings to my JSON file structure shown below: { "items": [] } To achieve this, I have the requirement of using the following code: var items = require("../../config/item.json"); The approach I am taking is ...

Error: The document object is not defined when attempting to access it within a

<script type="module" src="/scripts/navbar.js"></script> <script> async function fetchContent(e) { e && e.preventDefault(); const response = await fetch('https: ...

Different techniques for using percentages in CSS transformations to create dynamic animations for DOM element translations

I have 14 objects positioned across the dom that I need to animate using the translate property. Currently, I am using transform: translate(x%, y%) for each object, requiring me to calculate the translation amount and apply a CSS style individually. This m ...

Transforming JSON arrays into object representations

I have a collection of components structured like this: var names = 1)"lat: 40.6447077, lng: -73.878421, address: 1600 Pennsylvania Avenue, Brooklyn, NY 11239, USA" 2)"lat: 40.609099, lng: -73.931516, address: 2015 E. 35th street, Brooklyn, Ny, Un ...

Measuring data entries within JSON array utilizing JavaScript and Postman

A specific component is returning two records: { "value": [ { "ID": 5, "Pupil": 1900031265, "Offer": false, }, { "ID": 8, "Pupil": 1900035302, "Offer": false, "OfferDetail": "" } ] } My task i ...

Retrieving information from mlab without needing to make a new request, for example, updating the front end without refreshing the page

I understand that many people have asked questions similar to mine, but my issue is unique. I am trying to retrieve data from my mlab database without having to reload the page. For example, when a new cricket score is added to my db in mlab, I want this s ...

jQuery behaving erratically following deployment to the testing server

I am encountering an issue with jQuery in a user control that utilizes a Telerik RadGrid: <script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.4.js"></script> <script type="text/javascript"> ...

Angular does not support the transmission of nested objects within objects

When I use Angular.js to send this JSON to my node.js/express.js service: { "name": "MyGuitar", "type": "electric", "userid": "123", "likes": 0, "dislike": 0, "guitarParts": { "body": { "material": "/content/img/hout.jpg", "_id": "5566d6af ...

JavaScript functioning properly in Google Chrome and Firefox but not in Internet Explorer 9

Welcome to the Lottery random generator tool! Feel free to use this in Google Chrome or Firefox, but please note that it may not work properly in Internet Explorer 9. If you encounter any issues while using this tool on IE9 and receive an error message st ...

Centering loaders within elements of an unordered list

I am working on a navbar that uses Bootstrap 3 and AngularJS. Within this navbar, I have an unordered list with li elements. Below is a snippet of my navbar: https://i.stack.imgur.com/o75Lp.png This is the code for my navbar: <div class="navbar-head ...

Exporting components as the default from Next.js leads to a forced page refresh whenever there is a change

One issue I encountered involved having an index.tsx file containing all the shared UI components. When I exported the Footer and imported it into my shared Layout.tsx, which is utilized across all pages, the browser would refresh the page every time a cha ...

Exploring the world of React-Bootstrap elements and properties

I'm currently diving into a Bootstrap home project and it's my first time working with Bootstrap. I came across a tag that has an 'inverse' attribute among others like 'fixedTop', 'fluid', and 'collapseOnSelect& ...

The comparison between using multiple Vue.js instances and components, and implementing Ajax tabs

I am looking to incorporate ajax tabs using vue js. Each tab will need an ajax request to fetch both the template and data from an api. Here is an example of the tabs: <div id="tabs"> <ul class="nav nav-tabs"> <li class="active">& ...

Capture each touchdown and convert it to currency format

As a novice in the field of JS, I have put in a lot of effort into learning from various sources such as websites, documentation, friends, and other questions on Stack Overflow. However, despite all my efforts, I seem to be stuck at this point. $(docume ...

Is there a way to stop the execution of myFunc after it has been performed 5 times using clearInterval?

This code is designed to notify online shoppers that they need to choose a color from a dropdown menu before adding an item to their shopping cart. If no color is selected, the text will blink to alert them. How can I modify this code so that the blinking ...

What steps can be taken to troubleshoot and resolve this specific TypeScript compilation error, as well as similar errors that may

I am struggling with this TypeScript code that contains comments and seems a bit messy: function getPlacesToStopExchange(): { our: { i: number; val: number; }[]; enemy: { i: number; val: number; }[]; //[party in 'our' | 'enemy' ]: ...

Javascript textfield button function malfunctioning

Here is the code I have created: HTML: <form method="post" id="myemailform" name="myemailform" action="form-to-email.php"> <div id="form_container"> <label class="descriptio ...

There is currently no graph being shown

I've run this code but I'm not getting any output. There are no errors showing up, but I can't seem to figure out what's wrong. Can someone help me identify the issue? Thanks! <!DOCTYPE html> <html> <head> <m ...

Navigating - Utilizing dot-notation to reach the top-level function in Express

If we want to use express in a basic javascript file, all we need to do is add the following two lines of code at the beginning (after installing it through npm): var foo = require('express'); var app = foo(); According to the express API guide ...

Issue arises when isomorphic-dompurify is used alongside dompurify in Next.js 13 causing compatibility problems

I am currently facing a compatibility problem involving isomorphic-dompurify and dompurify in my Next.js 13 project. It appears that both libraries are incompatible due to their dependencies on canvas, and I am struggling to find a suitable alternative. M ...