Prevent accidental selection when clicking on empty space on a webpage using CSS

Can anyone help me with a frustrating issue I'm facing on my website? Whenever I click multiple times on empty spaces, it ends up selecting entire rows and paragraphs like in this fiddle.

The most confusing part is that there's no text under the cursor (such as the empty green area), so I don't understand why it would select anything at all.

In simple terms: I want default text selection behavior when clicking on actual text, but I don't want anything to be selected when clicking on non-text areas. Is there a way to achieve this?

Here is the HTML code for reference:

<div>
    <span>Clicks:</span> <input id="clicks" value="0"></input>

    <div style="background-color:LightGreen"
        onclick="$('#clicks').val(parseInt($('#clicks').val()) + 1);"><span class="hard">CLICK THE GREEN AND CLICK IT HARD!</span>
    <br/>
       <img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcS5lQfEXNPKzMGZRHUQJJJj97NFoi1Q4iZ_dT1GK9lrYsjrgd7i5XWsrTA"></img>
       <div style="width: 100%; display:inline-block"><span>more text</span></div>
    </div>
    <span>even more text</span>

    <p id="log"></p>
</div>

Answer №1

To tackle this issue, we can utilize the power of CSS' user-select.

If you want to test out the suggested solution, head over to this fiddle.

The approach starts by disabling text selection across the board:

/**
 * Prevent text selection across the website.
 */
body {
    -webkit-user-select: none; /* for webkit (safari, chrome) browsers */
    -moz-user-select: none; /* for mozilla browsers */
    -khtml-user-select: none; /* for webkit (konqueror) browsers */
    -ms-user-select: none; /* for IE10+ */ 
}

Subsequently, we examine all HTML elements and explicitly allow text-only elements:

/**
 * Whitelist strictly "pure text" elements according to HTML5 standards.
 * @see http://www.w3schools.com/tags/
 */
 a, abbr, address, b, bdi, bdo, blockquote, br, button, caption, center, 
 cite, code, col, dd, del, dfn, dt, em, figcaption, footer, h1, h2, h3, h4, 
 h5, h6, i,  input, ins, kbd, label, legend, mark, output, p, pre, q, rp, rt, 
 ruby, s,  samp, small, span, strike, strong, sub, summary, sup, td, textarea, 
 th, time,  title, tt, u, var {
    -webkit-user-select: text; /* for webkit (safari, chrome) browsers */
    -moz-user-select: text; /* for mozilla browsers */
    -khtml-user-select: text; /* for webkit (konqueror) browsers */
    -ms-user-select: text; /* for IE10+ */
 }

This technique allows users to select text intentionally without inadvertently selecting empty spaces. In case any non-selectable text is encountered, enclosing it within a <span> should do the trick.

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

New inputs cannot be accepted by the form

HTML <form action="./Login.php" method="post" onsubmit="return checkInput();"> <table width="300" border="1"> <tbody> <tr> <th> UserName: </th> <td><input class="box" type="text" value="" name="uname" id="uname ...

The click event will not be triggered if the element is removed by my blur event

My dropdown list is dynamic, with clickable items that trigger actions when clicked. Upon focus, the list displays suggested items When blurred, the list clears its contents The issue arises when blur/focusout events are triggered, causing my element to ...

Issue with Bootstrap card "sub-components" such as card-heading not functioning

I'm facing an issue while trying to integrate BlazorStrap into an existing .NET6 Blazor web assembly app. It seems like there is a problem with Bootstrap that needs to be resolved before I can get BlazorStrap to function properly. Let's focus on ...

Creating intentional blank space before the <Span> element using CSS in HTML

Currently working on a table with some spanned elements for customization. One issue I am facing is the persistent blank space above the blue spanned element in grid 6. Even when adding more spans to grid 6, they just jump below the blue one. How can I mak ...

Are HTML attribute names really case-sensitive? A topic filled with conflicting information

After learning that attribute names are case-sensitive, I found conflicting information. A source mentioned that attribute names are indeed case-sensitive. For example, the width attributes in <div> and <DIV> would be considered separate due ...

The feature of Jquery click and cursor: pointer only focuses on a single element at a

Recently, I created a navbar that includes a dropdown feature. I encountered an issue where I wanted the dropdown to show up when clicking on the navbar-profile class (which contains the profile picture, name, and chevron icon) in the top right corner. Ho ...

The page background appears to be incomplete in its coloring

As I work on creating a web application for personal use, my goal is to ensure it is mobile-friendly. However, I've encountered an issue where the background of my language page isn't displaying in full blue color as intended. Despite trying diff ...

The collapse feature of Bootstrap 5 navbar is experiencing delays

Can anyone assist me with the bootstrap navbar collapse issue I am facing? When I click on the burger menu, there is a slight delay of less than a second before it fully expands. Additionally, if I click very quickly multiple times on the burger icon, the ...

Creating a legitimate svg element using javascript

While working with SVG, I had an issue where I added a <rect> element directly into the svg using html, and then created a new element (without namespace) <circle> with javascript. However, the <circle> element did not display in the svg ...

How can CSS be utilized to style the visited links that are hovered over

Is there a way to change the font color specifically for visited hyperlinks that are being hovered over by the mouse? I am trying to achieve this: a:visited:hover {color: red} ...

Personalize Bootstrap 5 slider for mobile (displaying multiple items without being arranged in a single row)

Having trouble customizing the carousel layout for mobile devices. I'm trying to display all items of the carousel on mobile instead of just one. I've been experimenting with CSS and JS, specifically with the display, float, or max-width properti ...

Concealing Columns in the Beta version of Bootstrap 4

Currently utilizing Bootstrap 4.0 Beta for website design, encountering a roadblock with a responsive-utility feature. In previous Bootstrap 3 versions, it was achieved using classes like: hidden-xs, hidden-md, among others. The addition of -up and -down ...

Is it possible to modify the numerical values within TimeCircles.js?

I have integrated the TimeCircles.js plugin into a Persian website and need to convert Persian numbers to English. I already have a function that replaces each digit with the appropriate English number. I am able to successfully convert the text inside t ...

Attempting to remove options in a Multiple Choice scenario by selecting the X icon beside each one

I'm working on a multiple choice quiz and I'd like to add a button or icon resembling X in front of each option (even in front of the radio button), so that when I click on it, only that specific option is deleted. How can I achieve this? For in ...

Unique style CSS (Flex)Grid with spacing and uniform aspect ratio

Hello everyone, typically I'm quite skilled when it comes to CSS but this particular challenge has pushed me to my limits. I have a desire to create a grid where all elements maintain the same aspect ratio (with images that already share this aspect ...

The glow shader for front face is not displaying correctly in Chrome, but it functions fine in other web browsers

I have encountered an issue where I am attempting to apply a custom shader material to a series of nested objects in order to create a glow effect around each node. The effect works perfectly on my personal laptop (running Windows 8.1 and the latest versio ...

Utilize jQuery to assign a value to a <div> element

So, I'm dealing with this HTML div element: <div style="height:100px; width:100px" class="total-title"> initial text </div> I wrote some jQuery to update it: $('div.total-title').html('updated content'); Howeve ...

CSS - The 'object-fit: cover' attribute isn't functioning properly within the HTML email content

Could you please assist me with my html email body issue regarding the "object-fit: cover;" parameter? It works perfectly when displayed on the web, but is not functioning correctly in an html email body. EmailProvider: New Outlook in WIN PC Mobile: Also ...

Creating a switch statement that evaluates the id of $(this) element as a case

I have a menu bar with blocks inside a div. I am looking to create a jQuery script that changes the class of surrounding blocks in the menu when hovering over a specific one. My idea is to use a switch statement that checks the ID of $(this) and then modif ...

A missing definition for req.body.object

The issue with the req.body.object variable persists. Even though I have body parser imported, the value remains undefined when I try to console.log() it. //javascript const express = require('express'); var bodyParser = require('body-pa ...