Vanilla JavaScript: toggling text visibility with pure JS

Recently, I started learning javascript and I am attempting to use vanilla javascript to show and hide text on click. However, I can't seem to figure out what is going wrong. Here is the code snippet I have:

Below is the HTML code snippet:

<p class="h5 font-weight-normal">some text<span id="toggle-content" class="toggle- 
content" aria-hidden="true">some other text</span></p>
<a class="text-danger toggle-button" aria-controls="toggle-content">show more</a>

Here is the javascript code snippet:

const a = document.querySelector('.toggle-button');

if(a) {
  a.addEventListener('click', () => {
    const content = document.querySelector('.toggle-content');
    const ariaHidden = content.getAttribute('aria-hidden');

    content.setAttribute('aria-hidden', ariaHidden === 'true' ? 'false' : 'true');

    const buttonText = content.getAttribute('aria-hidden') === 'true' ? 'Show' : 'Hide';

    a.innerHTML = `${buttonText} more`;
  });
}

And finally, this is the CSS code snippet:

.toggle-content {
  display: none;
}

.toggle-content[aria-hidden="false"] {
  display: block;
}

Answer №1

You recently included a line break within the

<p class="h5 font-weight-normal">some text<span id="toggle-content" class="toggle- <!-- here you have added a line break which should not be inside an attribute -->
content" aria-hidden="true">some other text</span></p>

const variable = document.querySelector('.toggle-button');

if(variable){
variableEventListener('click', () => {
const content = document.querySelector('.toggle-content');
const ariaHidden = content.getAttribute('aria-hidden');

content.setAttribute('aria-hidden', ariaHidden === 'true' ? 'false' : 'true');

const atext = content.getAttribute('aria-hidden') === 'true' ? 'Show' : 'Hide';

variable.innerHTML = `${atext} more`;
});
}
.toggle-content {
display: none;
}

.toggle-content[aria-hidden="false"] {
display: block;
}
<p class="h5 font-weight-normal">some text<span id="toggle-content" class="toggle-content" aria-hidden="true">some other text</span></p>
<a class="text-danger toggle-button" aria-controls="toggle-content">show more</a>

Answer №2

Issue with the first p tag, ensure it is written correctly. I suggest simplifying your method by adding/removing the active class to your element like this:

const button = document.querySelector('.toggle-button');
const content = document.querySelector('.toggle-content');

button.addEventListener('click', () => {
content.classList.contains('active') ? content.classList.remove('active') : content.classList.add('active');
});

.toggle-content {
display: none;
}

.active {
display: block;
}

Consider using document.onload if your element has not yet appeared to prevent issues like this. This function will be called when the document is fully loaded and ready.

Answer №3

It seems like an error was made. Please revise the following:

let content = document.querySelector('.toggle-content');

to:

let content = document.querySelector('#toggle-content');

or for optimal performance,

let content = document.getElementById('toggle-content');

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 could be the reason for the malfunction of this angular binding?

Looking at the HTML below: <input type="checkbox" name="person" [(ngModel)]="person.selected" /> This input is part of a ngFor loop. Testing has revealed that despite some values of selected being true and others false, all checkboxes appear check ...

Conceal Primeng context menu based on a certain condition

I'm struggling to prevent the context menu from showing under certain conditions. Despite following the guidelines in this post, the context menu continues to appear. My goal is to implement a context menu on p-table where it should only show if there ...

React version 18.2.0 and Next.js version 13 faced an issue with hydration failure due to the initial user interface not matching. This problem

Upon opening the page, I encounter an error when focusing on the input element right away. However, if I wait a few seconds before focusing on the input element, the error does not occur. Unfortunately, I have been unable to resolve this issue. Interesting ...

With Firefox, when submitting a form only the final repeated region value is $_POSTed and not all of them

There seems to be an issue with the code below when running it in Firefox. The problem occurs when passing the URL variable UserName. In Firefox, only the last record is being used from the record-set, regardless of which button is clicked. This page utili ...

Safari has trouble with AJAX cross-origin requests, while Chrome and Firefox handle them without issue

I am developing a Shopify app that utilizes script tags and requires an ajax call to our server to retrieve necessary information about the shop. While everything seemed to be functioning correctly, my colleague pointed out that it was not working on his i ...

Is it possible to remove htmlescape from the custom options in Magento? Can you specify which file showcases the custom

Looking to incorporate HTML into custom option labels for products on my Magento store. Unfortunately, Magento does not parse HTML by default when it is placed in the custom options interface. I suspect there may be a line like "$this->htmlEscape()" wit ...

When using Rails to render a JSON page remotely, the JavaScript AJAX handler fails to capture the response

My goal is to have a form that can post remotely and then receive JSON data back for my JavaScript to process. Below is the code I am using: <%= form_tag '/admin/order_lookup', remote: true, authenticity_token: true, id: "order-lookup-submit" ...

Plot the components of an array and calculate the instances that JavaScript executes

I have an array containing information about PDF files stored in a buffer. Let's imagine this array holds ten PDF files structured like this: [{ correlative: "G-22-1-06", content: <Buffer 25 50 44 46 2d 31 2e 34 0a 25 d3 eb e9 e1 0a ...

What is the most efficient way to query through a Firestore database containing 5,000 users?

We are currently facing a challenge with our staffing application, which is built using vuejs and a firestore database containing over 5,000 users. Our primary issue lies in the need for a more efficient layout that allows admins to search for users within ...

When the mouse hovers over, include a fade-in effect for the image

I am working with two overlapping images and have successfully implemented a function to display the second image on mouse hover. However, I am struggling to incorporate a CSS transition property for a smoother image transition effect. Currently, when the ...

Minimization tools for compressing CSS and JavaScript documents

After deploying my application, I noticed that the loading time has significantly increased. Is there a way to compress CSS and JS files? I include only the necessary code in each page and occasionally use minified versions of JS. Thank you. ...

Managing Asynchronous Operations in Vuex

Attempting to utilize Vue's Async Actions for an API call is causing a delay in data retrieval. When the action is called, the method proceeds without waiting for the data to return, resulting in undefined values for this.lapNumber on the initial call ...

Extjs: How to Select a Node After Creating a Tree Structure

I am facing an issue with my TreePanel where I want to preselect a specific node when loading it. The nodes are fetched from a remote json file and the tree structure loads correctly. However, the selected node is not getting highlighted and Firebug is sho ...

Obtain the unique identifier for every row in a table using jQuery

Apologies for not including any code, but I am seeking guidance on how to use an each() statement to display the ID of each TR element. $( document ).ready(function() { /* Will display each TR's ID from #theTable */ }); <script src="https:// ...

In order to verify the dynamic components within the table

I need assistance with validating dynamically created textareas. In the code below, I am able to validate only the first row but struggling to do so for the second row. How can I get all the row values validated? Thank you in advance. To generate dynamic ...

Error: Encountering difficulty locating the necessary stylesheet for import during the construction of an Angular15 build, while also utilizing Kendo UI

Following the update to Angular 15, I encountered an error while using Kendo UI for the UI controls. It appears that the use of the tilde key is now deprecated. ./src/styles.scss - Error: Module build failed (from ./node_modules/sass-loader/dist/cjs.js): S ...

Preserve the specific date and time in the designated timezone

Utilizing the react-datePicker library requires using new Date() as input. I need to save the user's selected date, time, and timezone in such a way that regardless of their location, they will see Feb 10 2024 02:00 BST in the Date Object. Currently, ...

The Parent Div is styled with a background color, and I would like the sub div to inherit the background from whatever is behind the

I have a website at . When you click on a blue tab (except the middle left one), a larger tab appears with two Divs inside. What I am trying to achieve is having the sub divs show what's behind the green Div, especially while it's in motion. This ...

How to create list item bullets with a star icon using reactstrap/react?

As a machine learning professional looking to enhance my frontend skills, I am curious about how to create list item bullets using a custom star bullet image. Could anyone please share a complete HTML/CSS example with me? Thank you in advance! ...

Creating a custom navigation bar that elegantly fades away with a smooth animation as you scroll down the page is a must-have

How can I create a navigation bar that disappears when scrolling, with a smooth animation? This is the progress I have made so far. HTML: <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="css/style.css" type="tex ...