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

Attempting to transmit multiple variables

Can anyone provide assistance with passing multiple variables from one page to another? I am able to pass a single variable, but I need to send more than one by clicking a link. Below is a snippet of my code containing the rows I want to transmit to the ne ...

Tips for aligning words on a single line

Encountering an issue with long words being split up in the middle of a line, as shown in this photo: https://i.stack.imgur.com/IxQi6.png This is the code snippet causing the problem: ineligiblePointsTableRows() { return this.state[PointsTableType. ...

Using The Telerik AJAX radComboBox to Retrieve the SelectedValue from a Secondary comboBox

I’m attempting to fill a Telerik AJAX radComboBox with the results from another. For example: comboBox1 – auto-completes and user makes a selection comboBox2 – user selects. Loads on demand. It uses the selected value from comboBox1 to populate its ...

Seems like ngAfterViewInit isn't functioning properly, could it be an error on my end

After implementing my ngAfterViewInit function, I noticed that it is not behaving as expected. I have a hunch that something important may be missing in my code. ngOnInit() { this.dataService.getUsers().subscribe((users) => {this.users = users) ; ...

What is the process for connecting an event to the <body> element in backbone.js?

Could it be done? For example, like this: ... interactions { 'click button' : 'performAction' } ... ...

When using ngClick with a parameter, the parameter is not being successfully passed

My table resembles a tree structure with two ng-repeats. <table> <tr ng-repeat-start="am in anArray"> <td><button ng-click="TheFunction(am)"></button></td> </tr> <tr ng-repeat-start="em in anotherArray"> < ...

When working with JavaScript and Node.js, it is not possible to access an object's index that is

Utilizing babyparse (PapaParse) in nodejs to convert CSV to JavaScript objects has been quite challenging for me. After processing, the output of one object looks like this: { 'ProductName': 'Nike t-shirt', ProductPrice: '14.9 ...

Insert more text following the existing content

Is it feasible to include text using pseudo-elements ::after or ::before to a specific word? For example, I am interested in placing a PDF icon consistently beside the word "Download". [PDF] Download Alternatively, are there other methods available? ...

Using Jquery to toggle the visibility of divs based on radio button selections

I am struggling to hide the divs with the radio buttons until their title is clicked on. However, I am facing issues as they are not showing up when their title is clicked on. Any assistance would be greatly appreciated. SPIKE <!DOCTYPE html> &l ...

What is the significance of a listener signaling an asynchronous response with a return of true, only to have the communication channel close before the response could be received?

Currently, I am developing a React application that involves the use of various npm modules. One of these modules is a self-built NPM package called modale-react-rm (available at this link). This package serves as a simple modal component that utilizes the ...

Why does Drupal's Advagg display several css and js files?

After installing the Advag module, I noticed that it is combining files, but there seems to be an issue: <link type="text/css" rel="stylesheet" href="/sites/default/files/advagg_css/css__sqX0oV0PzZnon4-v--YUWKBX0MY_EglamExp-1FI654__IOPiOtulrIZqqAM0BdQC ...

The loading of the module from was hindered due to an invalid MIME type restriction

Exploring a three.js example and encountering an issue when utilizing import within a JavaScript module. The error message displayed is: Loading module from “http://localhost:8000/build/three.module.js” was blocked because of a disallowed MIME type ( ...

Include a class in ul > li elements upon page load in Angular4

I attempted to add a class to each "li" element in an Angular4 page, but the class was not applied. Here is the relevant HTML code: <ul class="pagination"> <button class="previous" (click)="previous()">Previous</button> <button ...

Discover identical HTML elements

I have a simple HTML code that I would like to split into similar parts: <input id="checkbox1"><label><br> <input id="checkbox2"><label><br> <input id="checkbox3"><label><br> The desired result should ...

Adjusting the size of an object as the page dimensions change

I am looking to dynamically resize an element whenever the document resizes. For example, if a draggable div is moved and causes the document to scroll, I want to adjust the size of another element using $("#page").css('height','120%'); ...

Is there a way to streamline the form completion process on my website by utilizing voice commands through the user's microphone?

My webpage features a web form using Flask where users manually input their information that is then added to a table upon submitting. The current setup involves an autoplay video prompting users with questions, which they answer manually and then submit t ...

How about determining the map size based on Divine proportions?

Is there a way to make the map at https://codepen.io/sinanelms/pen/MqdNNY responsive to screen size changes? I attempted the following code but was unable to achieve the desired outcome. <style type="text/css"> body{ background:#fff;} #map ...

Are you experiencing a strange problem with the CSS button when hovering, clicking, or with the border?

Check out the code for this implementation on jsfiddle: https://jsfiddle.net/xuhang1128/cmkbu07s/2/ I utilized React and React-bootstrap to create it. .design2-statusMonitor { margin-top: 20px; .list-group-item { display: inline-block; ...

Lighthouse Issue: Facing PWA Challenges with a "Request Blocked by DevTools" Error

For hours now, I've been struggling to make Lighthouse work in Chrome for my initial PWA project. I feel completely lost as nothing seems to be making sense despite the basic code I have included below. The issue arises when I load the page normally ...

Parse a string in the format of "1-10" to extract the numbers and generate an array containing the sequence of numbers within the range

Looking to convert a string in the format "1-10" into an array containing the numbers within that range. Display the array on the screen using a for loop. For example, if "1-5" is provided, the resulting array should be: {1, 2, 3, 4, 5} Create a workflow ...