Can you restrict the selection of text to only the current element?

<div class="container">
<div class="item1">text text text in div element 1</div>
<div class="item2">text text text in div element 2</div>
</div>

Is there a way using HTML nodes, CSS, or JavaScript to restrict the selection of text within div.item2 if the selection was initiated from text in div.item1 and vice versa - starting from div.item2 and limiting it (preventing item1 from being selected)?

Answer №1

I devised a solution using some jQuery code:

let $items = $(".item")

$items
.mousedown( function() {
$(this).siblings().css({ "user-select" : "none" , color : "lightgrey"})
})
.mouseup( function() {
$items.css({ "user-select" : "auto" , color : "black"})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="container">
<div class="item">text text text in div 1</div>
<div class="item">text text text in div 2</div>
<div class="item">text text text in div 3</div>
<div class="item">text text text in div 4</div>
</div>

Answer №2

By using the user-select: contain property, you can achieve this effect. However, keep in mind that this feature is limited to certain browsers...

Check browser compatibility here

Answer №3

After encountering a problem, I devised a solution that worked well for my needs...

I had multiple scrollable divs (with the class txt) where users could select text, but only within one div at a time (while preventing selection in other parts of the page). To achieve this, I utilized CSS:

*,.noSelect{ user-select:none; }
.txt{ user-select:text; }

...and then monitored the selectstart event to identify the element where the selection began and promptly disable selection in all other divs:

document.addEventListener('selectstart',function(e){
  var selStartID=window.getSelection().anchorNode.parentNode.id;
  $('.txt').each(function(){
    if(this.id!=selStartID){$(this).addClass('noSelect');}
  });
});

Once the user finished interacting with the selection (copying/saving/etc), selection was re-enabled in all other elements:

$('.noSelect').removeClass('noSelect');

Anticipating user-select: contain; in CSS4

Mozilla suggests that CSS UI 4 will introduce a simpler solution with user-select: contain;... Currently, only IE supports this [A rare occurrence!]. A polyfill on github is available — although I have not personally tried it.

(css-tricks.com and Wikipedia provide differing perspectives on CSS4, with additional insights found elsewhere.)

Answer №4

The simplest method is using CSS:

.element1 {
  user-select: none;
  -moz-user-select: none;
  -khtml-user-select: none;
  -webkit-user-select: none;
  -o-user-select: none;
}
<div class="element1"> Unable to be selected</div>
<div class="element2"> Can be selected</div>

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

Error: The value of 'id' cannot be assigned to an undefined property

Recently, I've been delving into learning JS Express and decided to create a basic solution to handle GET / DELETE / POST / PUT requests. Everything was running smoothly until I encountered an issue with the POST router. Below is the code snippet for ...

What is the reason behind the NextJS logo not being displayed when accessing the page via its URL?

My logo isn't displaying on the /page URL View Screenshot Check out my components/LayoutWrapper.js import Image from 'next/image' import icon from '../assets/images/Icon.svg' <div className="flex items-ce ...

Mastering Protractor's end-to-end control flow and managing time outs

When testing an angular app using protractor, I encountered a strange issue recently. Every now and then, or since a recent update, protractor seems to stall or slow down significantly. After investigating the problem, I discovered that a simple someEleme ...

When implementing ReplaySubject in Angular for a PUT request, the issue of data loss arises

I seem to be encountering a problem with the ReplaySubject. I can't quite pinpoint what I've done wrong, but the issue is that whenever I make a change and save it in the backend, the ReplaySubject fetches new data but fails to display it on the ...

"Optimize your website by incorporating lazy loading for images with IntersectionObserver for enhanced performance

How can I use the Intersection Observer to load an H2 tag only when the image is visible on the page? Here is the JavaScript code I currently have: const images = document.querySelectorAll('img[data-src]'); const observer = new IntersectionObser ...

"Standard" approach for a Date instance

During my time in the Node REPL environment, the following output was displayed: > console.log(new Date()) 2023-08-15T09:21:45.762Z undefined > console.log(new Date().toString()) Sun Aug 15 2023 09:21:50 GMT+0000 (Coordinated Universal Time) undefine ...

How to redirect to a different page within the same route using Node.js

When attempting to access the redirect on the login route using the same route, I first call the homeCtrl function. After this function successfully renders, I want to execute res.redirect('/login'). However, an error occurs: Error: Can't ...

unable to gather information from suppliers

I'm currently building a login page with nextjs and spotify js, but I've run into the following error https://i.sstatic.net/cKiM8.png Here is the code snippet that is causing the issue: import React from 'react' import { getProviders ...

Next.js fails to load TailwindCSS

I am in the process of developing an app using tailwindcss and next.js First, I started creating the nextjs app, then I executed these commands: npm install -D tailwindcss postcss autoprefixer npx tailwindcss init -p Following that, I made adjustments t ...

"Encountering an Invalid hook call error with React-Leaflet v4 and Next.js 13

I am facing an issue following my update of Next.js from version 12 to 13, which also involved updating React from 17 to 18 and react-leaflet from 3 to 4. Within this component: ` function ChangeView({ center }) { const map = useMap(); map.setView( ...

What is causing the slider image to be the only element that is not adapting to different screen sizes?

I am currently using the flexslider from woothemes and I am unable to understand why the image is consistently wider than the content when the browser window is resized or when viewed on an iPad/iPhone. Upon inspection, I couldn't find any styles on ...

It is not permitted to incorporate the navbar.html file into any other modules

As someone new to web development, I have been facing challenges while working with Django This is the code for my project's modules. {% include 'navbar.html' %} <h1>projects template</h1> <p>Lorem Ipsum is simply dummy ...

Tips for keeping the hover effect of a sibling element in Material-UI

Card Component import image from "../../Assets/pic.jpg"; import React, { useState } from "react"; import { makeStyles } from "@material-ui/core/styles"; import Card from "@material-ui/core/Card"; import CardActionAre ...

What is the best way to incorporate responsive centered text into my HTML element using Bootstrap 4?

Is there a way to add a responsive centered text element to my <a> element without being affected by the overlay color? Also, is there an alternative method to using an extra overlay div in Bootstrap 4? Check out this link for more details. HTML & ...

When the JavaScript string retrieved from the database is null, it will be displayed as an empty string

Currently, my Ajax setup involves querying a database on the server with SELECT someColumn FROM someTable. The returned value of someColumn is then updated on the client side by using $('#someElement').text(someColumn); Everything works perfectl ...

Using jQuery to swap out text

Here's what I'm trying to achieve: var newValue = $('.TwitterSpot').text().replace('#', 'Blah Blah'); $('.TwitterSpot').text(newValue); I believe this code should replace all instances of "#" with "Blah ...

What is the process of comparing one regular expression against another in JavaScript?

I'm looking to check for matches between two regular expressions. To achieve this, I use the .test method on each one. If either of them returns true, I consider them a match. const regexify = (str) => new RegExp( '^' + str ...

What is the best way to position elements with CSS?

I need help aligning the arrows and images on the same line. Can anyone guide me on how to do this? (I'm using html5boilerplate). Desired Layout: Current Layout: Existing Code: HTML: <div id="linkbar"> <a><img src="./img/ar ...

Is it possible to adjust the width of the comment box on the Facebook "Like" button?

Is there a way to set the width of the comment box that appears after clicking the Facebook "Like" button? I know how to adjust the width of the button itself and related content, but can't find any options for the comment box: I've tried overri ...

decipher the string using various operators

Is it possible to explode a string using different operators? I am trying to extract every code (of varying sizes) between the brackets [ and ] Here are some examples of the different possibilities: const codes = [ '[5018902847][592][50189272809] ...