Steps for retrieving the currently selected text inside a scrolled DIV

An imperfect DIV with text that requires a scroll bar

For example:

<div id="text" style='overflow:scroll;width:200px;height:200px'>

<div style='font-size:64px;'>BIG TEXT</div> 
Lorem Ipsum is simply dummy text of the printing and typesetting 
industry. Lorem Ipsum    has been the industry's standard dummy text ever  
since the 1500s, when an unknown printer took a galley of type and scrambled it 
to make a type specimen book. It has survived not only five centuries, but also 
the leap into electronic typesetting, remaining essentially unchanged.
It was popularised in the 1960s with the release of Letraset sheets 
containing Lorem Ipsum passages, and more recently with desktop publishing software 
like Aldus PageMaker 
including versions of Lorem Ipsum.

</div>

As the scrollbar moves, the text changes (due to overflow:scroll), is it doable to only select the text currently visible?

Example: http://jsfiddle.net/cxgkY/15/

Updated: The content inside may have varying text sizes

Answer №1

I have created a simple demonstration that should meet your expectations: click here (supports various sizes too). The concept involves dynamically generating individual span elements for each word, and then, upon scrolling the div, determining which spans are within view (based on their vertical position), thereby updating the selection range in the document. If you need further clarification, feel free to ask.

Answer №2

Uncertain about your request to choose only the text within the current viewport, but a potential solution could look like this:

var elem = $("#text"),
    txt = $(elem).text().split(' '),
    htmlContent = [],
    selectedText = '';

$.each(txt, function(index, element) {
    htmlContent.push('<span>'+element+'</span>');
});

elem.html(htmlContent.join(' '));

$('span', elem).each(function(index, element) {
    if ($(element).offset().top < elem.height()) {
        $(element).css('background', 'red');
        selectedText += $(element).text()+' ';
    }
});

FIDDLE

If the aim of this task is simply to showcase the text in another container element, you can achieve that by mimicking it with the following code:

$("#text").on('scroll', function() {
    $('#visible').html($(this).html()).scrollTop($(this).scrollTop());
});

FIDDLE

Answer №3

Here is an example that you can try out (Check out the DEMO link: http://jsfiddle.net/cxgkY/14/):

HTML:

<div id="text">
    <div id="wrapper">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
    </div>
</div>

​ ​ JavaScript:

$('#text').scroll(function () {
  var text = $(this).text();

  var begin = $(this).scrollTop() / 
      $(this).children('#wrapper').height();

  var end = begin + $(this).height() /
    $(this).children('#wrapper').height();

  var text = text.slice(text.length * begin, text.length * end);
  $('#visible').text(text);
});  

Answer №4

<div id="text">
    <p>Line 1</p>
    <p>Line 2</p>
    <p>Line 3</p>

</div>

One way to achieve this is by using the following code:

$(function(){
    var meanLineHeight = $('#text > p').first().outerHeight();

    var result = $('#result');

    $('#text').scroll(function(){
        var linesScrolled = Math.ceil(this.scrollTop/ meanLineHeight);
        console.log(linesScrolled);

        var linesToSelect = $('#text > p').slice(linesScrolled);
        linesToSelect.css('background-color', 'yellow');
    });​​​​​​​
});

​Check out the demo here

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

Display all the names of the files from various file inputs in a unified notification

I have developed a function that checks if the selected file names already exist in the database. It currently alerts a message for each file name found in the database, which can be overwhelming with multiple files. I am looking for suggestions on how t ...

What could be causing the malfunction of removeEventListener in my Nuxt application?

Whenever a search result is displayed on my app, the component below renders and checks if the user scrolling is at the bottom of the page. Initially, the code works fine, but I encounter an error when returning to the page after navigating away and scro ...

What is preventing the selected values of a dropdown element from being set?

Although it may seem simple to assign values to select elements, I'm puzzled as to why the code below is setting the values to null instead of the correct ones for "form-type" and "genre". All other fields are being set correctly. It's worth not ...

Tips for implementing X-XSS-Protection: 1; mode=block in HTML

I'm struggling with where to place this piece of code in my existing code. Should it be added to the header section? <head> <meta content="text/html; charset=UTF-8; X-Content-Type-Options=nosniff" http-equiv="Content-Type" /> <title> ...

Clicking on a DIV using jQuery, with anchor elements

I have a method for creating clickable divs that works well for me: <div class="clickable" url="http://google.com"> blah blah </div> Afterwards, I use the following jQuery code: $("div.clickable").click( function() { window.location ...

Trouble with AJAX communicating with PHP and not rendering fresh data

I have created a row of images that are clickable, and once clicked, a variable is sent via AJAX to a PHP file for a database query. The PHP file receives the variable and executes the correct query. However, instead of updating the HTML on my page, it sim ...

Establish the predefined date for the air-datepicker

I am currently utilizing the air-datepicker inline feature. My objective is to establish the starting date for it. Below is the script detailing my attempt: export function load_datepickers_inline():void { const search_legs_0_datepicker = $("#search_leg ...

JavaScript - Receiving alert - AC_RunActiveContent.js needed for this page to function

When I attempt to open the HTML file in my application, a pop-up message appears stating that "This page requires AC_RunActiveContent.js." However, I have already imported and referenced the AC_RunActiveContent.js file in my package. Can someone assist m ...

Using a CSS nth-child selector to eliminate the bottom margin of the final row

As I work on creating lists that are displayed in columns of two, each .customer-review-container includes a margin-bottom CSS property like this: <div class="col-md-6"> <div class="customer-review-container"> </div> <!-- en ...

Leveraging Django's JSONResponseMixin for handling AJAX responses

I'm currently using Django in conjunction with AJAX. My goal is to have a javascript file (vote.js) POST data to a Django View, which will then respond with JSON data to be utilized by my javascript's callback function in the HTML. Below is the ...

Create a dynamically updating list using React's TypeScript rendering at regular intervals

My goal is to create a game where objects fall from the top of the screen, and when clicked, they disappear and increase the score. However, I am facing an issue where the items are not visible on the screen. I have implemented the use of setInterval to d ...

Is there a way to invoke a function in an iframe from its parent?

How can I call a function that is in an iframe from the parent document? If the function were in the parent, I could simply use parent.func(); but since it's within the iframe, how can I still call it successfully? JavaScript keeps saying it can' ...

Transferring data from a text area to a table with AngularJS

Creating a C# MVC App with AngularJS My goal is to populate a table with values entered in a text area using Angular. Here is the process: Users input values into a text area like this: A B C When a user clicks a button, a modal window should open and ...

Importing GeoJSON data into Meteor's Leaflet

Recently diving into Meteor, I am on a mission to create my own customized version of this impressive example from leaflet incorporated into Meteor: Interactive Choropleth Map The implementation requires the use of this GeoJson Data file: us-states The o ...

What is the best way to configure an EmailId validator in Angular 6 to be case insensitive?

My register and login page include a form validator pattern matching for the registration form. this.registerForm = this.formBuilder.group({ firstName: ['', Validators.required], emailId: ['', [Validators.required, Validators.patt ...

Move your cursor over the top and bottom of the image to experience distinct effects

Trying to create an effect where the top 50% of an image shows a different color and text when hovered over, and same for the bottom 50%. Currently, only able to achieve this effect for the lower half of the image. Is there a way to make it work for both h ...

Unable to retrieve event data and integrate it into HTML using jQuery

Just starting out with leaflet and JavaScript, jQuery. I've got an index.html page displaying a map, and want to show the coordinates of the mouse pointer underneath the map when it moves. To achieve this, I have a div element with the id "coordinat ...

The email verification process is experiencing technical difficulties

Having trouble displaying error message when emails do not match I am relatively new to PHP and could use some assistance. The $email variable captures the user's email input, while the $VerifyEmail variable does the same for email verification purp ...

Directive fails to trigger following modification of textarea model

There is a block of text containing newline separators and URLs: In the first row\n you can Find me at http://www.example.com and also\n at http://stackoverflow.com. The goal is to update the values in ng-repeat after clicking the copy button. ...

How can I eliminate the hover effect from a div element?

I am facing an issue with implementing a zoom effect on hover for my list of products. When I do a long press on a product, it works the first time but not the second time. I suspect this is because the div remains in a hover state. I want to ensure that ...