What is the process of generating clozed text using HTML and CSS?

Is there a method to conceal text and create an underline of identical length in an HTML document? In this technique, certain highlighted words remain hidden, substituted with underlines that match the original text's length precisely. Additionally, all sentence words should maintain their original locations even after clozing. For instance:

Once upon a time there ______ a cat.

The word intended for clozing may be indicated as follows:

Once upon a time there <div class="cloze">lived</div> a cat.

How can I implement text hiding and underline creation with matching lengths?

Answer №1

Implement CSS styling:

.hidden-text {
    border-bottom: 1px solid black;
    color: transparent;
}

Displaying hidden text using <span class="hidden-text">text</span>.

JS Fiddle Example

Answer №2

Expanding on @HoboSapiens' response (unfortunately, I am unable to comment due to my score), you might also consider utilizing the ::selection selector to prevent users from highlighting the text.

http://jsfiddle.net/Delorian/mm8tp1xb/

.clozed::selection {
    color: transparent; 
}

Keep in mind that even though users won't be able to highlight the text on the webpage, they can still view it in the source code. If you require a more secure solution, you may need to incorporate JavaScript on the client or server-side to replace the text. However, this approach would sacrifice the accuracy of underlining the text based on its width.

Answer №3

If you want to protect the original text from being seen in the source code, it's recommended to use PHP for this task.

However, if you prefer achieving this with JavaScript, you can follow these steps:

var spans = document.querySelectorAll('.clozed');
var words = [];

function repeatString(str, count) {
    var repeatedText = '';
    
    for (var i = 0; i < count; i++) {
        repeatedText += str;
    }
    
    return repeatedText;
}

var index, spanCount = spans.length;
for (index = 0; index < spanCount; index++) {
    var currentSpan = spans[index];
    var textContent = currentSpan.innerText = currentSpan.textContent;

    words.push(textContent);

    currentSpan.innerText = currentSpan.textContent = repeatString('_', textContent.length);
}

Check out this JSFiddle link for a live demo.

Remember: you can utilize the words array for validating the input at a later stage.

For an undo function, refer to this link: http://jsfiddle.net/0e7hw2a9/2/

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

Need to monitor a Firebase table for any updates

How can I ensure my Angular 2 app listens to changes in a Firebase table? I am using Angular2, Firebase, and TypeScript, but the listener is not firing when the database table is updated. I want the listener to always trigger whenever there are updates or ...

What is the best way to display a template after submitting data via AJAX in the Flask framework?

Encountering an issue where I am unable to open render_template after posting data with ajax. Below is my ajax code: if ($(this).attr("value") == "button-three") { var skoring = getRadioVal(document.getElementById('mentodeNegasi'),'neg ...

Nextjs is throwing an error: "Invalid element type. What steps can be taken to resolve this issue?"

While working on my Next.js app, I encountered the following error: Error - Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your co ...

Maintaining a consistent style input until it is modified

I'm currently dealing with this code (continuing from a previous question): input[type=submit]:focus { background-color: yellow; outline: none; } The issue I'm facing is that when I click anywhere else on the screen, the background color go ...

Replacing inline CSS with styled components in Next.js Sass modules

In order to display emoji icons in my Next.js App, I utilize the Twemoji library. These emojis are rendered as <span><img></span> elements in the final HTML output. To customize their default width and height, I use the !important rule in ...

Unveiling Elements as You Scroll Within a Specified Area

I have implemented a jQuery and CSS code to reveal my contact form as I scroll down the page. However, I am facing an issue with setting a specific range for displaying the element while scrolling. Currently, I have only managed to handle the scrolling dow ...

Issues with retrieving information between AJAX and PHP (and vice versa)

I have a script that sends the value of a text input from an HTML form to emailform.php. This PHP file then adds the data to a .txt file. The issue I'm facing is setting the value of $email in the PHP file to match that of the HTML input field. Curren ...

How can I alter the image using the success function in jQuery?

I'm encountering an issue with my jQuery voting script. Everything seems to be working correctly, except for the fact that the image in the success function of the AJAX request is not updating as expected. jQuery: $("a.vote_down").click(function(){ ...

Devices such as CAC cards and smart cards are not being recognized by Chrome's WebUSB feature

I recently developed a script to identify all USB devices connected to Chrome using chrome.usb.getDevices. Surprisingly, the script successfully detected a second-generation iPod touch, a mouse, keyboard, and two unidentified items from Intel. However, it ...

What is the best way to align the navigation with a maximum of three elements (lists) in a row using responsive design?

I've been trying various methods but haven't been able to center it while keeping the padding intact. It's a mobile navigation bar. Here is what my code is producing currently: [1]: https://i.sstatic.net/sHEjj.png This is how I want it to ...

Using Javascript to implement a min-width media query

I'm currently facing an issue with my website () where the media query (min-width) is not effectively removing a JavaScript code within a specific div. The HTML structure in question is as follows: <div id="advertisementslot1"> <script lang ...

Updating a slider based on the values of two other sliders can be achieved by implementing a

I am working on a project that involves three input sliders. I need the third slider to display the product of the values from the first two sliders. Additionally, I want the value of the third slider to update dynamically whenever the values of the first ...

Press the list button to reveal an enlarged box

Each item on this list contains a hidden box that should be shown after it is clicked. However, the issue arises when expanding one item causes other items to expand as well. Refer to the image for clarification: Image Link Is there a way to only expand ...

Ways to showcase HTML table in a four-column layout/grid

Delving into Dynamic HTML table creation, I'm currently using jquery for rendering purposes. At the moment, I am only displaying the table. The Goal I aim to segment my table into four columns or a grid structure Something akin to this: https://i. ...

Having issues with the CSS dropdown menu not activating when hovering

I am facing an issue with a simple menu that includes a dropdown feature upon hovering. The code works perfectly fine in Fiddle, however, it fails to work when running the entire page locally on IE. Can someone please assist me? (here's my code at fi ...

The issue arises when attempting to use input alongside debounce, event.persist(), and storing the value at the parent component

Is there a way to implement an input field with debounced search where the value is passed from the parent component? Currently, when I pass the value from the parent component it doesn't work as expected. What would be the correct approach to make th ...

The schema for model "User, userSchema" has not been registered, resulting in a MissingSchemaError. To fix this error, make sure to use mongoose.model(name, schema

Hey there, I hope everything is going well! I'm currently working through a tutorial from 2019 and running into an error. Here's the code snippet (let me know if you need more information): // index.js // const express = require('express&a ...

Is there a way to prevent the onClick event from executing for a particular element in React?

Currently working with Material UI, I have a TableRow element with an onClick event. However, I now need to incorporate a checkbox within the table. The checkbox is enclosed in a TableCell element, which is nested within the TableRow. The issue arises wh ...

HTML Element Split in Two by a Line in the Middle

Greetings to all, after observing for a while I have decided to make my first post here (and just to clarify, I am an electrical engineer, not a programmer). I am in search of creating a unique element in HTML where I can detect clicks on both its upper a ...

HTML5 for advanced positioning and layering of multiple canvases

I have 2 canvas layers stacked atop each other, but I need to position them relative to the entire page. The dimensions of both layers are fixed at a width of 800 and a height of 300. My goal is to center the canvas layers regardless of screen size, with ...