Switching HTML text by clicking or tapping on it

I'm currently working on a website that will showcase lengthy paragraphs containing complicated internal references to other parts of the text. For instance, an excerpt from the original content may read:

"...as discussed in paragraph (a) of section (2) of chapter one thousand and fourteen of this article about modern art."

My aim is to present this information in a more concise format, like so:

"...as discussed in Ch. 1014(2)(a) regarding modern art."

However, I want users to have the option to switch between my shortened version and the full original text by clicking or tapping on the text. Ideally, the abbreviated text would be highlighted or outlined to indicate that it can be expanded for more details.

Does anyone have suggestions on how I could implement this feature? Should it be done using HTML, CSS, jQuery, JavaScript, or another method?

(Just to clarify, I don't need an automated algorithm to generate short forms; I can manually input them as needed.)

Thank you!

Answer №1

If you need to display short snippets of text, such as a single sentence, consider storing the longer version in a data attribute within a span tag. Then, utilize jQuery to swap out the text inside the span tag with the content stored in the data attribute.

HTML

<p>
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce enim 
    nisl, elementum sit amet tortor eu, finibus tristique libero. Quisque 
    eget varius magna. Suspendisse sodales vitae ligula eget pellentesque. 
    <span data-long-text="Aenean pharetra ut massa non volutpat">Aenean 
    123</span>. Vivamus eu viverra eros. Aliquam condimentum lacus odio, 
    sit amet vulputate sem lacinia id. Suspendisse ultrices, lectus ut 
    volutpat cursus, justo risus aliquet lectus, hendrerit interdum massa 
    arcu at ipsum.
</p>

CSS

span[data-long-text] {
    border-bottom: 1px dotted red;
    cursor: pointer;
}
// optional styling changed to long text
.long-text[data-long-text] {
    border-bottom-color: green;
}

jQuery

$('[data-long-text]').on('click', function(e) {

    var $this = $(this);
    var short = $this.text(); // text in span tag
    var long  = $this.attr('data-long-text'); // text in data- attribute

    // text values swapping places
    $this.text(long);
    $this.attr('data-long-text', short);

    // optional styling change
    $this.toggleClass('long-text');

});

jsFiddle: http://jsfiddle.net/hp383q1t/

Answer №2

https://jsfiddle.net/1gLv5qyv/

Implement the following function:

$(".text-toggle").click(function(){
    $(".toggleAble").toggle();
});

This code utilizes the JQuery plugin for toggling elements.

Answer №3

To hide text on a webpage, create a CSS class with the property display:none. Assign an ID to the class and then use jQuery to toggle the class on and off.

Answer №4

To implement this functionality, you would utilize HTML, CSS, and jQuery (JavaScript) in the following manner:

...as mentioned in section (a) of part (2) of chapter 1014 within this article focusing on contemporary art.

a.ref {
    background: yellow;
    color: black;
    text-decoration: none;
}
$('.ref').click(function (e) {
    var refData = $(this).attr('data-att');
    var refText = $(this).text();
    e.preventDefault();
    $(this).text(refData);
    $(this).attr('data-att', refText);
});

$('.ref').click(function (e) {
    var refData = $(this).attr('data-att');
    var refText = $(this).text();
    e.preventDefault();
    $(this).text(refData);
    $(this).attr('data-att', refText);
});
a.ref {
    background: yellow;
    color: black;
    text-decoration: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>...as discussed in <a href="#" class="ref" data-att="Ch. 1014(2)(a)">section (a) of part (2) of chapter 1014</a> within this article focusing on contemporary art.</p>

Answer №5

If I were not considering SEO, my approach would be to store both long and short descriptions in a data attribute. This way, you can focus on correctly defining your HTML structure.

http://example.com

HTML

<p class="has-expanded-text">
     ...as discussed in <span class="toggle short" data-short-
     description="Ch. 1014(2)(a)" data-long-description="subparagraph 
     (a) of subdivision (2) of chapter one thousand and fourteen of this 
     article"></span> concerning modern art.
</p>

CSS

.toggle { color: blue; text-decoration: underline; cursor: pointer; }

jQuery

$('p.has-expanded-text').each(function(index){
    var $span = $(this).find('.toggle'),
        $short = $span.data('short-description'),
        $long = $span.data('long-description');

    $span.text($short); // sets default text to short description

    $span.click(function(){
        if($span.hasClass('short')){
            $(this).addClass('long').removeClass('short');
            $(this).text($long);
        }
        else{
            $(this).addClass('short').removeClass('long');
            $(this).text($short);
        }
    });
});

Answer №6

Utilizing jQuery, CSS, and vanilla JS can make this idea a reality

HTML:

<p class="first">your initial text</p>

<p class="additional">extra content</p>

CSS:

.additional { display:none; }

jQuery:

jQuery('.first').click(function(){
    jQuery(this).hide();
    jQuery('.additional').show();
});

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

Challenges faced when integrating Angular with Bootstrap elements

I am currently in the process of developing a website using Angular 12, and although it may not be relevant, I am also incorporating SCSS into my project. One issue that I have encountered pertains to the bootstrap module, specifically with components such ...

Manually detecting changes in the query string using AngularJS

My AngularJS application includes an edit form with a routing URL like app/edit/:id. When I navigate to app/edit/5, I am able to edit the object with ID 5. However, if I manually change the URL to app/edit/6, the application loads the object with ID 6 in ...

enhancing the appearance of the initial sentence in the closing passage through CSS styling

Is there a way to make only the first sentence in the final paragraph bold using CSS? Specifically, I would like to add extra padding to the top of this last paragraph so that it wraps around an image. However, when I increase the bottom padding of the flo ...

The deep reactivity feature in Vue3 is functioning well, however, an error is being

I am currently using the composition API to fetch data from Firestore. While the render view is working fine, I am encountering some errors in the console and facing issues with Vue Router functionality. This might be due to deep reactivity in Vue. Here is ...

Using jQuery or JavaScript in an ASP.NET environment, you can make the parent list item of a dropdown link active

Welcome to my navigation menu <ul class="sidebar-menu" id="navigation-menu"> <li class="active"><a class="nav-link" href="/"><i class="fas fa-home"></i><span>Home Page</span></a></li> <li cl ...

Multiple occurrences of setting the state on an array result in logging an empty array each

My current challenge involves fetching data from a backend server and storing it in an array. However, when I attempt to pass this array to another component, I encounter an issue where multiple empty arrays are being passed instead of one filled with data ...

What is the best way to relocate a child component to a different parent in React?

I have a list of child components with checkboxes, and when a checkbox is clicked, I want to move that child component inside another div. Below is an illustration of how my app should look. I need to select student names and shift them up under the "Pres ...

Ways to enhance focus on childNodes using Javascript

I am currently working on implementing a navigation system using a UL HTML Element. Here's the code I have so far: let htmlUL = <HTMLElement>document.getElementById('autocomplete_ul_' + this.name); if (arg.keyCode == 40) { // down a ...

Swift code in WKWebView shows increased word spacing in lengthy Arabic texts

Having long Arabic text within <p> tags in my HTML file (loaded by WKWebView) on my app results in unusually large word spacing and unreadable text. In Xcode, the letters in the HTML file appear disconnected. Is there a way to prevent this issue with ...

Issue with verifying file existence utilizing $.ajax()

I'm currently facing a challenge checking for the existence of a file using $.ajax(). I am cycling through a JSON file with $.each and trying to determine if a specific staff member has an image. If not, I want to default to using the no_photo.jpg ima ...

Exploring the significance of a super in Object-Oriented Programming within JavaScript

During my studies of OOP in JS, I encountered the super() method which serves to call the constructor of the parent class. It made me ponder - why is it necessary to invoke the parent class constructor? What significance does it hold for us? ...

Enhancing search results with data retrieved from a jSON response

At the moment, I am using a logic to generate a list of titles. Now, I would like to include data from the response along with the code for each title in the list. const title = responseData.map(item => { return { label: item.title, val ...

Graphics distorting on android devices when implementing createjs and canvas technology

I have a question regarding the performance of my game that I'm developing to work on both desktop browsers and mobile devices. Using HTML5 and CreateJs, most of the game is being drawn on a canvas element. While everything runs smoothly on a standar ...

The issue arises when attempting to apply CSS styles to an existing component or body tag,

I am currently working on an Angular 7 project where I have a requirement to dynamically load a component using routes. However, when I try to add styles for the body tag and existing component tags in the dynamically loaded component style-sheet, they do ...

Validate an object to check for null or empty fields, including arrays, using Javascript

Currently, I am facing an issue with iterating through a complex array that contains objects and embedded arrays. The goal is to detect any empty or null values within the array. However, my challenge lies in accurately determining if an array is empty. De ...

Iterating through a legitimate JSON object and storing each data value in a separate variable

I am currently utilizing jQuery. To further elaborate on my previous question, I have executed an Ajax request using the jQuery $.ajax function with a PHP script. The PHP script returned a JSON object which was validated when tested with link text. I am p ...

What is the best way to mark a MenuItem as active within a Material UI Drawer component?

Here is the code snippet I am working with: <Drawer docked = {false} width = {330} open = {this.state.drawerOpen} onRequestChange = {(drawerOpen) => this.setState({drawerOp ...

String includes another String not refreshing automatically

How come myCtrl.greeting doesn't automatically update when I change myCtrl.name? angular.module('MyApp', []) .controller('MainController', [function(){ var mCtrl = this; mCtrl.name = ''; mCt ...

This JavaScript operates in solitude, unable to collaborate with other JavaScripts

I received this code from an outsourced programmer: <script type="text/javascript"> $(function(){ $('#notif-icons > li > a, #top-menu > li > a').click(function() { var clicked = $(this).next('.popup-notif&a ...

What is the best way to organize table rows into a single column when the window is resized?

I am working on a table that has three pictures in a row, with 100% width. I want the table to be responsive and stack the pictures into one column when the space is limited. The issue I am currently facing is that the elements of the table do not stack i ...