Hassle with iOS Phonegap selecting multiple lines of text?

For my Phonegap app, I need users to be able to select and modify text inside a p element.

The issue arises when trying to select text within the p tag. The text is fetched from my server and displayed as follows:

<p style="white-space:pre-wrap">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec eget laoreet magna. Quisque eu urna nec turpis imperdiet ultricies. Fusce vel libero id justo fringilla tincidunt. Nullam egestas nisi justo, et dapibus odio tempor eget. Mauris convallis orci at mi volutpat placerat. Nullam scelerisque fermentum efficitur.
</p>

This format allows line breaks without using <br/> tags, which do not function properly in my JavaScript code.

However, when attempting to select text in this element, the entire p element is selected instead of specific words. This creates confusion for users as shown below:

Please note: The text differs in the images due to different content, but the selection issue remains consistent.

I cannot provide a live example on jsFiddle as the problem only occurs within the Phonegap environment. You can access the source files for testing here: Source Files

The project does not contain any JavaScript, and the HTML and CSS structures are as follows:

HTML:

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
        ...
    </head>
    <body>
        <p class="text">Sample Text Here...</p>
    </body>
</html>

CSS:

.text{
    white-space:pre-wrap;
    word-wrap: break-word;
    height:300px;
    overflow: scroll;
    -webkit-overflow-scrolling: touch;
    padding:10px;
    border:1px solid #000;
    background-color:#fff;
}

One solution I considered was using contenteditable="true" on the p element, but it has limitations such as:

  1. Restriction on creating additional tags within the element
  2. Inability to display the keyboard

Another approach I explored was removing the pre formatting. However, this removes line breaks that I prefer to retain.

Answer №1

The issue lies in the way iOS's selection engine works with text - it selects either individual words or entire elements. Since your text is contained within a single <p> element, the native selection engine will choose the entire <p> element when attempting to select multiple lines. To address this, you need to provide a "hint" to the selection engine indicating that you want to be able to select multiple lines. This can be achieved by placing each line of text into its own block level element, such as a <div>.

Below is an example script that extracts text from the <p class="text"> element and places each line of text into a separate <div> element while preserving new lines, empty lines, and leading spaces using non-breaking-space character entities.

var textElm = document.getElementsByClassName("text")[0],
    text = textElm.textContent,
    html = "";

html = text.replace(/([\t ]*)(.*)\n/g, function(match, spaces, text) {
    if (spaces === "" && text === "") spaces = " "; // Ensure empty lines are displayed by adding a single &nbsp; to the <br> element
    return "<div>" + Array(spaces.length + 1).join("&nbsp;") + text + "</div>"
});

textElm.innerHTML = html;

Once this restructuring is done, you can safely remove white-space:pre-wrap; from the CSS since it will no longer be necessary.

Answer №2

To resolve this issue, one solution is to enclose the entire text within a p tag or any other container, and then replace traditional line breaks (<br />) with a faux-line break created using the following code:

<a class="space"></a>

This faux-line break can be styled by applying the following CSS:

.space{
    display:inline-block;
    height:15px;
    width:100%;
}

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

Limit the text input area in HTML to a fixed size, preventing any text from exceeding the specified boundary

Is there a way to create a fixed line text area that limits the user from typing beyond a certain number of lines and maximum width? My current CSS styling for this is as follows: .area-style { resize: none; width: 324px; height: 200px; m ...

Try fetching new data with React Query by refetching

Whenever a button is clicked, I attempt to fetch new data by calling Refetch. const {refetch,data,isLoading} = useQuery( "getkurs",() =>fetch( `https://free.currconv.com/api/v7/convert? q=${selected.country.currencyId}_IDR&compa ...

Accessing html form elements using jQuery

I'm having trouble extracting a form using jQuery and haven't been able to find a solution. I've tried several examples, but none of them display the form tags along with their attributes. Here is a sample fiddle that I've created: Sam ...

Expanding the hover state of a Bootstrap button

I am currently working on a website with bootstrap 4 and I am utilizing the bootstrap cards, which includes the primary button (btn-primary). My goal is to trigger the hover state of the button when hovering over the card itself. Is there a way to achieve ...

Retrieving the value of a duplicated button in AngularJS

I have implemented a basic HTML table using AngularJS to display data for each item in my "names" array. Each item represents an object with various attributes such as Name, id, etc. Along with each row in the table, I have included a button. However, I am ...

Relax with Express.js nested router

If I want to create REST endpoints with the following structure: /user/ /user/user_id /user/user_id/items/ /user/user_id/items/item_id Performing CRUD operations on each endpoint seems logical. For instance, a POST request to /user creates a new user, ...

The validation for decimal numbers fails to function when considering the length

I've been struggling to come up with a regular expression for validating decimal numbers of a specific length. So far, I've tried using pattern="[0-9]){1,2}(\.){1}([0-9]){2}", but this only works for numbers like 12.12. What I'm aimin ...

What could be causing my UITableView content to rearrange every time it is refreshed?

tag, I have a peculiar issue with my UITebleView and custom UITableViewCells. Whenever I refresh them, the content seems to reorder itself. Can anyone shed some light on why this might be happening? I am fetching the data from a JSON source, and I'm ...

Is there a way to showcase AJAX responses in the exact sequence they were dispatched, all without relying on queuing or synchronous requests?

I'm facing a challenge with sending out multiple getJSON() requests to a remote server in order to retrieve images. The issue is that the responses arrive asynchronously, causing them to be displayed in a mixed-up order. While I could make the reques ...

Guidelines for sending data as an array of objects in React

Just starting out with React and I have a question about handling multi select form data. When I select multiple options in my form, I want to send it as an array of objects instead of an array of arrays of objects. Can anyone help me achieve this? import ...

Obtain the URL linked to the button that was just clicked

As a newcomer to jQuery, I have a question: For instance, on a webpage with a voting feature, when a button is clicked, a counter is increased by +1. Now, how can the URL of this button be displayed on a website? This way, if the URL is shared with others ...

The Nextjs Image was preloaded using link preload, but it remained unused after a short period following the window's load event

I've encountered an issue while working with Next.js, a React-based framework. I am attempting to display the logo.png image using the Image component provided by Next.js. My image is stored in this folder: public/img Here is the code I'm using ...

Iterate through an array of objects, applying a filter and simultaneously generating a new object

I have an array of elements structured like the example below. In this structure, there are nested rows within input, and each rows object contains an array of objects. let input = [ { "title": "ENGINEERING", "rows": [ { "ri ...

Adjust the width of the column to only contain fixed content and not span the entire page

Check out my solution on Plunkr to see the issue I'm facing: Plunkr I'm dealing with a layout that includes a menu on the left and page contents on the right. My goal is to have the menu fixed in place so that it doesn't move when the page ...

Optimizing the If operator in JavaScript to function efficiently without causing the page to reload

While delving into jQuery and attempting to create a slider, I encountered a problem. After the slider passed through the images for the second time, the first image would not appear. My approach involved using margin-left to move the images. $(document ...

The contents of the image are currently unable to be viewed

I have a Blob of an image that I am trying to display in the browser. However, when I use the code below to open the image, it shows some Mandarin scripts on the window. Here is the code snippet: var url="http://....link..../downloadFile?fdsFileId="+file ...

I keep encountering a 404 error page not found whenever I try to use the useRouter function. What could

Once the form is submitted by the user, I want them to be redirected to a thank you page. However, when the backend logic is executed, it redirects me to a 404 page. I have checked the URL path and everything seems to be correct. The structure of my proje ...

Need to create a callback within a sequence of events?

Is it possible to create a callback chain like this? Widget.update(...).onUpdate(function(data){ console.log('updated'); }); Here is the current code snippet: var Gateway = {}; Gateway.put = function(url, data, callback) { $.ajax({ ...

Center a list-group with text and dropdown using Bootstrap 4 vertical alignment

I am relatively new to using Bootstrap 4 and I am encountering challenges in vertically aligning certain elements within a list-group. Specifically, I have text on the left side and a dropdown on the right. <div class="dashboard-blocks"> <ul cl ...

Is there a method in Discord.JS to remove an embed from a message sent by a user?

Currently, I am developing a bot utilizing the Discord.JS API. This bot is designed to stream audio from specific YouTube links using ytdl-core. Whenever a link is typed in, an embed of the YouTube video appears. While there are methods to disable embeds o ...