"Enhance your website with a 'Read More' link using

I'm in the process of creating a simple example for displaying hidden content with a "Read More" button. The setup includes a paragraph and a button, with half of the text inside a span tag that is initially hidden. However, I have been able to implement the code successfully but now I am looking to add a fade-in effect using pure JavaScript instead of jQuery. Can anyone offer assistance with this?

var span = document.getElementsByTagName('span')[0];
var hideshow = document.getElementById('hideshow');

span.style.display = 'none';

hideshow.onclick = function() {
  span.style.display = 'block';
};
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa maiores dolore earum ducimus molestiae, aut. <span>Quisquam consequuntur, maiores et, doloremque atque provident similique consequatur totam voluptas vitae veniam, molestiae laborum.</span></p>

<button id="hideshow">Read More</button>

Answer №1

One method involves utilizing a CSS3 transition to smoothly change the opacity of an element.

In this scenario, when the button is clicked, the class fade-in is applied to the child span element.

var button = document.querySelector('.read-more');

button.addEventListener('click', function(event) {
  var span = event.target.previousElementSibling.querySelector('span');
  span.classList.add('fade-in');
});
.show-more span {
  display: inline-block;
  height: 0;
  overflow: hidden;
  transition: opacity 2s;
  opacity: 0;
}
.show-more span.fade-in {
  height: auto;
  opacity: 1;
}
<p class="show-more">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa maiores dolore earum ducimus molestiae, aut. <span>Quisquam consequuntur, maiores et, doloremque atque provident similique consequatur totam voluptas vitae veniam, molestiae laborum.</span></p>
<button class="read-more">Read More</button>

If you need a solution that applies to multiple elements, you can also consider the following:

var buttons = document.querySelectorAll('.read-more');

for (var i = 0; i < buttons.length; i++) {
  buttons[i].addEventListener('click', function(event) {
    var span = event.target.previousElementSibling.querySelector('span');
    span.classList.add('fade-in');
  });
}
.show-more span {
  display: inline-block;
  height: 0;
  overflow: hidden;
  transition: opacity 2s;
  opacity: 0;
}
.show-more span.fade-in {
  height: auto;
  opacity: 1;
}
<p class="show-more">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Ipsa maiores dolore earum ducimus molestiae, aut. <span>Quisquam consequuntur, maiores et, doloremque atque provident similique consequatur totam voluptas vitae veniam, molestiae laborum.</span></p>
<button class="read-more">Read More</button>

<p class="show-more">Another shorter paragraph. <span>Quisquam consequuntur, maiores et, doloremque atque provident similique consequatur totam voluptas vitae veniam, molestiae laborum.</span></p>
<button class="read-more">Read More</button>

Answer №2

Let's begin here

alpha.style.opacity = 0;

The goal is to smoothly transition the opacity until this point.

alpha.style.opacity = 1;

To achieve this, you must implement an asynchronous approach (setTimeout/setInterval/requestAnimationFrame) for iteration, as using a synchronous method (while/for/for-in/forEach) will cause the main thread to be blocked, hindering the browser from effectively rendering the element with the updated opacity.

function fadeTo(element) {

  function adjustOpacity() {
    if(element.style.opacity < 1) {
      requestAnimationFrame(adjustOpacity);
      element.style.opacity = Number(element.style.opacity) + 0.05;
    }
  }

  adjustOpacity();
}

Alternatively, if you prefer utilizing CSS instead of pure JS, you can accomplish this by employing classes and transitions.

.hidden {
  opacity: 0;
  transition-duration: 0.5s;
}

.visible {
  opacity: 1;
  transition-duration: 0.5s;
}

Ensure that the element initially has the hidden class upon entering the DOM, then when you're prepared to reveal it, switch it to the visible class, allowing the browser to manage the animation seamlessly.

Answer №3

let fadeDuration = 2000; // milliseconds

document.getElementById('hideshow').addEventListener('click', () => {
   requestAnimationFrame((startTime) => {
      let animateFade = (currentTime) => {
         let progress = (currentTime - startTime) / fadeDuration;
         if(progress < 1) && requestAnimationFrame(animateFade);
         span.style.opacity = 1 - progress;
      }
      animateFade(startTime);
   })
}  

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 use JavaScript to fill in missing images with alternative HTML content?

As a provider of a service that helps users find the location of pictures, I face a challenge due to the fact that the pictures are stored on another internal site. Some users may not have access to this site as my service offers additional information. Th ...

ReactJS - What makes ReactJS unique compared to other technologies?

Hey there! I'm currently trying to figure out why this specific code snippet was successful while my previous one wasn't. I've included both snippets below: SUCCESSFUL CODE: handleInputChange = (e) => { let { value } = e.target; ...

What could be the reason for this XSS script not making a request to my server?

Currently diving into the realm of XSS attacks to enhance my knowledge on application security. My goal is to extract the user's cookie from a local website and then transmit it to my local server for testing purposes. I've successfully obtained ...

The custom CSS cursor appears to be displaying in a pixelated manner

Trying to experiment with custom cursors, but every attempt ends up pixelated. I created a ring asset to demonstrate the issue. Here is the cursor image file. cursor: url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/272259/circle.png), auto; Although it ...

Ways to limit the width of content

While I could use a div container to solve this issue, I'm exploring the possibility of achieving it without one. My goal is to create a layout that is flexible between 640px and 1280px, but remains fixed beyond that range. The colored div I have cur ...

The code below is not working as it should be to redirect to the home page after logging in using Angular. Follow these steps to troubleshoot and properly

When looking at this snippet of code: this.router.navigate(['/login'],{queryParams:{returnUrl:state.url}}); An error is displayed stating that "Property 'url' does not exist on type '(name: string, styles: AnimationStyleMetadata". ...

What's the reasoning behind incorporating a superscript esf in the Zap Chance typeface?

I'm working with a sample HTML file that includes the Zap Chance font. <!DOCTYPE html> <html> <head> <style> @font-face { font-family: myFirstFont; src: ...

Utilizing a 'for' loop to add a listener for a 'click' event

HTML: <li>Facebook</li> <li>Twitter</li> <li>Souncloud</li> JS: var links = ['https://www.facebook.com/', 'https://twitter.com', 'https://soundcloud.com']; function openURL (url) { l ...

Utilizing the power of JavaScript within CSS styling

I may be new at this, so excuse the silly question, but I'm currently working on developing an app with phonegap. In order to ensure that my app looks consistent across all devices, I need to define the height of each device. I know that JavaScript ca ...

The group icon will dynamically change based on the selection made in the dropdown menu

I am currently working on a Bootstrap dropdown select for weather in my Razor Pages project. My goal is to have the input group icon change dynamically based on the selected weather option. For example, I want to display a cloudy icon when the user selects ...

Send a pair of viewmodels to the function

My work involves dealing with e-commerce shopping carts. I have implemented two view models for this task. The first view model is for customer information: public class CartViewModel { public string FirstName{get;set;} public string Emai ...

What is the JavaScript event object all about?

Can you provide an example of what is considered an 'event object' in the context of this program? Is it, for instance, the <p> element if a <p> is clicked, or the <html> element if <html> is clicked? Or is the event objec ...

Dynamically changing click events in VueJS can be achieved using a combination of

Once component B has finished loading, I trigger an "emit" event to notify component A using EventBus. When A receives the event with a value of "on", it updates a specific data value to true. This value is stored in a computed property and can only be a ...

Executing a console.log statement within an array nested inside a function of an object

Today in school, I learned about objects and how a function inside an object is actually called a method. In my method, I have an array and I'm trying to change a global variable to display a different location in the console.log. However, all I keep ...

Node.js JSDOM unable to locate the 'parsingMode' property in the code

Is there a way to interact with the DOM of a JavaScript file using Node.js? var fs = require('fs'); var jsdom = require('jsdom'); var doc = jsdom.jsdom(fs.readFileSync("a.html"), null, { features: { FetchExt ...

Musical backdrop for an online game platform

Currently, I am working on developing a game using HTML. I am trying to figure out the best way to incorporate music into the gameplay. Any suggestions on how I can add music to my web-based game? ...

When a node using express encounters :id, it is directed to a specific location

Currently, I am in the process of creating a small API collection to familiarize myself with nodejs using express. In my project, I have included the line app.use("/v1/phrases", phraseRouter); Within the router file, the code looks like this: co ...

REG: Identifying Custom Dropdown Boxes with CAPYBARA

Currently, I am facing a challenge when trying to select a value from a custom dropdown menu that contains numerous options. The issue arises when attempting to choose values beyond the first one due to excessive padding spaces in the text. While my code ...

Tips for manipulating deeply nested arrays of objects within an array with JavaScript

I need assistance with calculating the average of ratings within nested array objects that are inside another array. Below is the array provided: let arr = [ [{"category":"behavioural", "rating":3}, {"category":& ...

Include a condition to check the value of each row (angular material)

I am facing an issue where I need to apply a condition based on the value of the current column, but I am unable to access the value of the current row. I am unsure which variable to use in order to check the condition. I tried using 'row' but it ...