How can I make all child elements within a div uneditable?

Is there a way to make an entire div and all of its child elements uneditable without individually setting each one to readonly? This div contains a lot of dynamic content and I need a simple solution to prevent editing. If I set the parent div to readonly, will all the child elements automatically follow suit?

Providing some background, the reason for this is to prevent a text field within the div from triggering the mobile keyboard to pop up. My goal is to ensure that the entire web app remains uneditable, thus avoiding any unwanted behavior.

Answer №1

To prevent the on-screen keyboard from popping up, you can apply the readonly attribute to all input and textarea elements within a specified wrapper. This will allow the elements to be focused on but not allow any input values to be entered.

In cases where the keyboard appears due to the autofocus attribute or an earlier executed script, changing the inputs to readonly after they have already received focus may not resolve the issue. In such scenarios, you can check for focus and redirect it elsewhere within the wrapper to effectively close the keyboard.

const wrapper = document.getElementById("wrapper");

wrapper.querySelectorAll("input, textarea").forEach(element => element.setAttribute("readonly", ""));

// Set focus on the wrapper if the active element is inside it, to reset any open on-screen keyboard
if (wrapper.contains(document.activeElement)) {
  wrapper.focus();
}
<div id="wrapper" tabindex="-1">
  <form>
    <p>
      <label>Text input
  <input type="text" value="Lorem ipsum">
  </label>
    </p>
    <p>
      <label>Email input
  <input type="email" value="<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8ffbeafcfbcfeaf7eee2ffe3eaa1ece0e2">[email protected]</a>" autofocus>
  </label>
    </p>
    <p>
      <label>Select input
  <select>
    <option>Option 1</option>
    <option selected>Option 2</option>
  </select>
  </label>
    </p>
    <p><a href="#">A link</a></p>
  </form>
</div>

Answer №2

If you want to make text unselectable but still allow pointer events, you can use user-select: none;. This is different from pointer-events: none;:

p {
  user-select: none;
}

p:hover {
  color: purple;
}
<div>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus nulla risus, eleifend a dolor eu, rutrum sagittis ex. Donec sit amet odio sollicitudin, dictum lectus vel, pretium ipsum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices
    posuere cubilia curae; Nam volutpat sodales ornare. Sed elementum dapibus neque a varius. Quisque ultrices imperdiet ante, quis posuere leo mattis eu. Ut sollicitudin turpis non urna tempor volutpat. Nam sed lorem a risus consectetur aliquet. Cras
    non erat semper, molestie dui id, pharetra metus. Aenean aliquet tortor sapien, non efficitur libero suscipit non. Phasellus condimentum, justo vel pulvinar maximus, mauris ipsum aliquet enim, vitae porttitor orci massa sit amet eros. Nulla ultrices
    purus sed nibh fringilla, sit amet ultrices justo malesuada. Donec accumsan vel ante ut sollicitudin. Nulla faucibus ante quis sem vestibulum, vitae gravida tortor lobortis.</p>
</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

Mongodb: Search for IDs within a nested array field

My MongoDB data structure includes user profiles with friend request information. Here's an example: { _id: "someId", profile: { username: "oliv", friendRequests: [ { fromUserId: "anId", accepted: false, created: " ...

The correlation between frames per second (FPS) and the milliseconds required to render a frame in the stats plugin is known as the frame

Recently, I've implemented the Stats.js plugin to keep track of my three.js performance. Something seems off with the FPS (frames rendered per second) and MS (milliseconds needed to render a frame) information: According to my calculations, if it ta ...

Storing references to the DOM elements external to the rendering component

Just diving into the world of Electron + Typescript, so please bear with me. Currently, I'm experimenting with what can be achieved within Electron. Issue: My goal is to manipulate DOM elements outside of the renderer. I pass a button as a parameter ...

Utilize the ng.IFilterService interface within a TypeScript project

I am facing an issue with a .ts file that contains the following code: module App.Filters { export class SplitRangeFilter implements ng.IFilterService { static $inject = ['$filter']; public static factory(): Function { ...

Trouble with Three.js: Issue with loading textures by name

I have a file with a .obj extension that I am currently loading using a loader. This file contains multiple meshes which I want to use separately as individual objects. The challenge I am facing is that each of these objects has a distinct texture. However ...

Load website content in real-time

My website requires dynamic content to be loaded on user interaction. When a user clicks certain elements on the page, information should be retrieved from a file located in the same directory as the webpage and displayed in a designated <div>. My u ...

Calling functions in AngularJS/HTML can help you execute specific

Just started with angularjs and facing some major issues haha... I have something that seems to be working fine, but I can't figure out what's wrong with this code... can someone please help me? Here it is: Basically, the scope.create function ...

"Optimizing Image Display in Web Browsers

Currently, I am using JavaScript to dynamically size a transparent .gif on my website. The original image size is approximately 200x200 pixels, but it's usually resized to be between 600x600 and 800x800. When viewing the resized image in IE8 and FF3, ...

JavaScript unable to locate ASP button ID with the method "findbyelementID"

Trying to locate the ID of an ASP.Net control in JavaScript is proving challenging as it keeps showing "ID not found." While I have reviewed various related questions, they all pertain to ASP forms or similar, whereas I am utilizing DIV tags here, resultin ...

Troubles arising from React component integration with Gatsby JS

As I dive into creating a stunning portfolio website with Gatsby js, I encountered an issue while trying to integrate the card component from the gatsby-plugin-material-ui package. The card resides in a separate file within my components directory and is e ...

When transferring files to the src/pages directory in Next.js, the custom _app and _document components are not recognized

The documentation for Next.js mentions that the src/pages directory can be used as an alternative to /pages. However, I encountered a problem when moving my custom _app.tsx and _document.tsx files into the src folder, as they were being ignored. If you cr ...

What is the best way to eliminate items from an array in a side-scrolling video game?

In my gaming project, I am creating a unique experience where the player needs to collect all the words from a given array. Currently, I am utilizing the shift() method to eliminate elements, as demonstrated in the code snippet below: if ( bX + bird.width ...

Exploring methods to retrieve data from the web3 platform through Node.js

Is there a way to retrieve token information such as name, symbol, and decimals using Nodejs in conjunction with web3js? ...

Exploring discrepancies in jQuery AJAX responses between Chrome and Firefox

As someone who is not a front-end developer, I find myself working on a casual project that involves using AJAX to retrieve a piece of JSON data. $('#btn1').click(function() { $.ajax({ url: 'http://mywebsite.com/persons/mike&apo ...

What steps can I take to ensure my CSS component remains unaffected by the global CSS styles?

My navbar component is not displaying the styles correctly as intended. I have a Navbar.module.css file to style it, but after using next-auth for social login, only the buttons remain unstyled while everything else gets styled. The code snippet for impor ...

Service error: The function of "method" is not valid

In one of my Angular 2 applications, I have a class that contains numerous methods for managing authentication. One particular method is responsible for handling errors thrown by the angular/http module. For example, if a response returns a status code o ...

Why does my node-js API's second endpoint not function properly?

Currently working on my first API project. Everything was going smoothly, until I encountered an issue with my second route, app.route('characters/:characterId'). For some reason, none of the endpoints are functioning, while the first route, app. ...

Issue with parameter functionality not working as expected

This code snippet is not functioning as expected. I am trying to extract and print the values from the URL parameter file:///C:/Users/laddi/Desktop/new%201.html?t=vindu&b=thind function GetURLParameterValue(param) { var pageURL = window. ...

Framer Motion does not support animations for exiting elements

Why is it that when I specify the exit property of framer motion to my HTML elements, they fail to animate upon being removed from the DOM? Here's an example of what my code looks like: <motion.div initial={{opacity: 0, y: -500}} animate={ ...

The jQuery slider comes to a gradual halt

I can't figure out why my jQuery slider doesn't stop right away after a mouseover event. There seems to be a delay that I can't resolve on my own. Can someone lend a hand with this problem? Here is the code I'm working with: https://js ...