Display additional content following a <p></p> segment

I am facing an issue with my script for displaying more text. The problem is that the "Show more" link appears right after the text in my structure.

My desired setup is to have the "Show more" text appear right at the end of the existing text. However, since I will be using Tinymce to generate the text, I am unable to modify the text directly.

You can view how I want the "Show more" text placement to look like in this image.

An example of what I am looking for can be seen here: Show More Example

Here is my HTML/JavaScript code:

document.addEventListener('DOMContentLoaded', function() {
  new ShowMore('example-1', {
    more: ' ... Show more',
    less: ' Show less'
  })

});

//showMore.min.js
var ShowMore = (function() {
  // JavaScript logic goes here
})();
<div class="container">

  <section id="example-text">
    <h2>More text</h2>
    
    <div class="example-1" data-type="text" data-number="500" data-after="1">
      <p><strong>Porque &eacute; que o usamos?</strong></p>
      <p>&Eacute; um facto estabelecido de que um leitor &eacute; distra&iacute;do pelo conte&uacute;do leg&iacute;vel de uma p&aacute;gina quando analisa a sua mancha gr&aacute;fica. Logo, o uso de Lorem Ipsum leva a uma distribui&ccedil;&atilde;o mais
        ou menos normal de letras, ao contr&aacute;rio do uso de "Conte&uacute;do aqui, conte&uacute;do aqui", tornando-o texto leg&iacute;vel. Muitas ferramentas de publica&ccedil;&atilde;o electr&oacute;nica e editores de p&aacute;ginas web usam actualmente
        o Lorem Ipsum como o modelo de texto usado por omiss&atilde;o, e uma pesquisa por "lorem ipsum" ir&aacute; encontrar muitos websites ainda na sua inf&acirc;ncia. V&aacute;rias vers&otilde;es t&ecirc;m evolu&iacute;do ao longo dos anos, por vezes
        por acidente, por vezes propositadamente (como no caso do humor).</p>
      <p><strong>O que &eacute; o Lorem Ipsum?</strong></p>
      <p>O Lorem Ipsum &eacute; um texto modelo da ind&uacute;stria tipogr&aacute;fica e de impress&atilde;o. O Lorem Ipsum tem vindo a ser o texto padr&atilde;o usado por estas ind&uacute;strias desde o ano de 1500, quando uma misturou os caracteres de
        um texto para criar um esp&eacute;cime de livro. Este texto n&atilde;o s&oacute; sobreviveu 5 s&eacute;culos, mas tamb&eacute;m o salto para a tipografia electr&oacute;nica, mantendo-se essencialmente inalterada. Foi popularizada nos anos 60 com
        a disponibiliza&ccedil;&atilde;o das folhas de Letraset, que continham passagens com Lorem Ipsum, e mais recentemente com os programas de publica&ccedil;&atilde;o como o Aldus PageMaker que incluem vers&otilde;es do Lorem Ipsum.</p>
      <p><strong>De onde &eacute; que ele vem?</strong></p>
      <p>Ao contr&aacute;rio da cren&ccedil;a popular, o Lorem Ipsum n&atilde;o &eacute; simplesmente texto aleat&oacute;rio. Tem ra&iacute;zes numa pe&ccedil;a de literatura cl&aacute;ssica em Latim, de 45 AC, tornando-o com mais de 2000 anos. Richard McClintock,
        um professor de Latim no Col&eacute;gio Hampden-Sydney, na Virg&iacute;nia, procurou uma das palavras em Latim mais obscuras (consectetur) numa passagem Lorem Ipsum, e atravessando as cidades do mundo na literatura cl&aacute;ssica, descobriu a
        sua origem. Lorem Ipsum vem das sec&ccedil;&otilde;es 1.10.32 e 1.10.33 do "de Finibus Bonorum et Malorum" (Os Extremos do Bem e do Mal), por C&iacute;cero, escrito a 45AC. Este livro &eacute; um tratado na teoria da &eacute;tica, muito popular
        durante a Renascen&ccedil;a. A primeira linha de Lorem Ipsum, "Lorem ipsum dolor sit amet..." aparece de uma linha na sec&ccedil;&atilde;o 1.10.32.</p>
      <p>O peda&ccedil;o mais habitual do Lorem Ipsum usado desde os anos 1500 &eacute; reproduzido abaixo para os interessados. As sec&ccedil;&otilde;es 1.10.32 e 1.10.33 do "de Finibus Bonorum et Malorum" do C&iacute;cero tamb&eacute;m est&atilde;o reproduzidos
        na sua forma original, acompanhados pela sua tradu&ccedil;&atilde;o em Ingl&ecirc;s, vers&otilde;es da tradu&ccedil;&atilde;o de 1914 por H. Rackham.</p>
    </div>

  </section>

</div>

Answer №1

Here's a great idea to transform the last <p> into an inline element on the screen so that the More/Less button can appear right behind the text:

From an earlier comment:

A simple solution is to make the last p element display as an inline box:

div.example-1 p:last-of-type{display:inline;}
. Even better, attach the link directly to the last p element instead of inserting it after. Check out the demo here - G-Cyrillus 25 mins ago

document.addEventListener('DOMContentLoaded', function() {
  new ShowMore('example-1', {
    more: ' ... Show more',
    less: ' Show less'
  })

});

//showMore.min.js
var ShowMore = (function() {
  // JavaScript code here...
})();
div.example-1 p:last-of-type {
  display: inline;
}

b {
  color: #0095E5
}
<div class="container">

  <section id="example-text">
    <h2>More text</h2>

    <div class="example-1" data-type="text" data-number="500" data-after="1">
      <p><strong>Why do we use it?</strong></p>
      <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. Using Lorem Ipsum leads to a more or less normal distribution of letters, unlike "Content here, content here", making it readable
        text. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for "lorem ipsum" will uncover many websites still in their infancy. Various versions have evolved over the years, sometimes
        by accident, sometimes on purpose (humour injected).</p>
      <p><strong>What is Lorem Ipsum?</strong></p>
      <p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book.
        It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
        desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
      <p><strong>Where does it come from?</strong></p>
      <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked
        up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et
        Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet...", comes from a line in section
        1.10.32.</p>
      <p>The most widespread Lorem Ipsum text used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also presented in their original form, accompanied by an English translation
        dating back to 1914 by H. Rackham.</p>
    </div>

  </section>

</div>

Alternatively, experiment with positioning: Check it out here, it positions it all the way to the far right at the bottom.

Answer №2

To achieve this effect, I'm utilizing a simple positioning solution. The approach involves setting the parent div with position:relative;, and then applying position:absolute; to the span element.

document.addEventListener('DOMContentLoaded', function() {
  new ShowMore('example-1', {
    more: ' ... Show more',
    less: ' Show less'
  })

});

//showMore.min.js
var ShowMore = (function() {
  // Code goes here
})();
<div class="container">

  <section id="example-text">
    <h2>More text</h2>
    
    <div class="example-1" data-type="text" data-number="500" data-after="1">
      <p><strong>Why do we use it?</strong></p>
      <p>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using "Content here, content here", making it readable text. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for "lorem ipsum" will uncover many websites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).</p>
      <p><strong>Where does it come from?</strong></p>
      <p>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cities of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet...", comes from a line in section 1.10.32.</p>
      <p>The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English versions from the 1914 translation by H. Rackham.</p>
    </div>

  </section>

</div>

Answer №3

A simple and effective solution is provided below:

.sample-1{
   position:relative;
}

.sample-1 span{
    position: absolute;
    right: 0;
    bottom: 0;
}

For an even quicker fix, consider the following option:

.sample-1 p:nth-child(2){
   display:inline;
}

Answer №4

Changing the p tag to a span element will prevent the "show more" text from starting on a new line, as demonstrated by testing in developer tools.

<div class="container">

  <section id="example-text">
    <h2>Additional Text</h2>
    
    <div class="example-1" data-type="text" data-number="500" data-after="1">
      <p><strong>Why do we use it?</strong></p>
      <span>It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many websites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humor and the like).</span>
      <p><strong>What is Lorem Ipsum?</strong></p>
      <span>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</span>
      <p><strong>Where does it come from?</strong></p>
      <span>Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet...", comes from a line in section 1.10.32.</span>
      <span>The standard chunk of Lorem Ipsum used since the 1500s is reproduced below for those interested. Sections 1.10.32 and 1.10.33 from "de Finibus Bonorum et Malorum" by Cicero are also reproduced in their exact original form, accompanied by English translations from the 1914 version by H. Rackham.</span>
    </div>

  </section>

</div>

Give this solution a try!

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

What is the best way to send a distinct identifier using JavaScript or PHP?

I am looking for a way to replace "INSERT+ORDER+ID" with a unique ID when a user clicks on our "Request Information" button to improve visitor tracking. Can anyone provide guidance on how to achieve this? Your assistance is greatly appreciated, thank you ...

In my JavaScript code, I am parsing a JSON file and attempting to extract the data associated with a specific key

Here's the javascript code I'm working on. I am looping through a JSON file and trying to access the 'bought_together' values nested under 'related', but my current code doesn't seem to be doing what I want it to do. To d ...

The issue with JSON and asynchronous JavaScript requests

I've been trying to work on this for hours, but I can't seem to figure it out by myself. For a project, I need to use JSON, and even though I was able to make it work, the data is not being returned to the correct JSP; instead, it's just di ...

Incorporate a CSS attribute into your code using the cssText method in JavaScript

By using JavaScript, I successfully added an attribute to the HTML tag with the following code: document.documentElement.style.cssText = 'cursor: url("https://image0.png"), auto !important;'; This resulted in the following CSS being ap ...

Experiencing an "ENOTFOUND" error after attempting to make a large volume of API calls, possibly in the range of 100,000, to maps.google

I have a requirement to send a large number of requests to https://maps.googleapis.com/maps/api/place/queryautocomplete/json. Currently, I am fetching lists of strings from multiple files and sending requests to the mentioned API. When I test with 100 str ...

What is the best way to defer the instantiation of a particular controller (not a route) in your

What I'm looking for is a directive that functions like a typical ng-controller, but I need it to be invoked only after a promise has been resolved. To achieve this in HTML, it could be implemented as such: <div ng-controller="myCtrl" ctrl-promise ...

Updating HTML content using jQuery by iterating through an array

When I write the following HTML code: <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script> <h1 id="message"> </h1> and include the corresponding JavaScript code: messages = ["Here", "are", ...

What is stopping me from utilizing ES6 template literals with the .css() method in my code?

I am currently working on a project where I need to dynamically create grid blocks and change the color of each block. I have been using jQuery and ES6 for this task, but I am facing an issue with dynamically changing the colors. Below is the snippet of m ...

Use CodeMirror on an existing div element

My div named "content_editable" is the center of my code editing application. I need it to adhere to specific CSS dimensions, but I also want to integrate CodeMirror syntax highlighting into it. However, following the documentation's instructions does ...

Tips for making the cursor invisible when only the background is visible

I am trying to hide the cursor when only the background is displayed in HTML/CSS, but unfortunately, it is not working as expected and the cursor still appears over the background. Here is my code: body { background: url('https://miro.medium.c ...

CSS - Using the left float property inline

.htabs { /* horizontal tabs */ display: table; } .htabs li { /* horizontal tab */ position: relative; float: left; background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAYAAADgzO9IAAAAMklEQVQIW2M8e3r/fw4OdgZk8OPHTwbGq5eP/Q ...

Secure Your Knockout JS Applications with These Development Tools

In my MVC / SPA application, I have implemented several knockout functions where variables are assigned to allow them to be called from other functions. This setup enables updating elements on the page and making server calls when necessary. All primary k ...

"Troubleshooting Problem with JSON Encoding in PHP and Parsing with getJSON in

Apologies if this sounds like yet another discussion on the topic, but I've been struggling for hours without finding a solution. I'm attempting to retrieve data from a MySQL database, generate a JSON using PHP, and then parse this JSON in JavaS ...

Bracketing the Webpage: A Display of Unique Design

Currently, I am utilizing the Brackets code editor to create a webpage in HTML format. My aim is to transfer these files to another computer so that the user on that device can view the webpage created from these HTML files. Strangely, when I open the HTML ...

Storing Redux state in local storage for persistence within a React application

Recently, I've been experimenting with persisting data to local storage using Redux. My approach involved creating an array of alphabet letters and setting up an event listener to log a random letter each time it's clicked. However, despite succe ...

Crafting centered and uniform width flex elements in Bootstrap 4

As someone still new to bootstrap, I've been exploring two main layout options: flex and grid. Right now, I'm working with the flexbox method, but I've hit a roadblock in terms of width. My aim is to design three rows (although my code only ...

What is the correct npm identifier to include in the package.json file?

I am looking to make my library accessible on NPM for the first time. I want it to be available publicly, so in the package.json file of my library, I have "name": "firstname-lastname/testlib123" This means my first name - my last n ...

The function in the method (in quasar) is not activated by the @change event

When I select an option, I am trying to retrieve the selected value in a function called within my methods. However, the function does not seem to be triggering. This is my code: From the template : <q-select filled v-model="invoice_product.tarri ...

Updating the state of a parent component from a slot in VueJS

Hi there, I am currently facing a challenge as a newcomer to Vue. Within my project, I am using Vuetify and have a v-dialog component with a slot structured as follows: <template> <v-row> <v-dialog v-model="dialog" max-width="600px"&g ...

magnify within a div with a set width

Looking for a way to make a div both zoomable and scrollable within a fixed-width container using transform: scale(aScaleRatio) for zooming in/out. Check out this demo for achieving the zoom effect. However, the inner div seems to have trouble aligning to ...