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

The paths specified in Node.js and Express are having difficulty finding the resource files for CSS and JavaScript

I am currently using Express to develop a basic website. Everything was running smoothly until I attempted to add the following code to handle 404 errors: app.get('/*', function(req, res) { res.render('404.ejs',{ title: ' ...

Tips for passing a distinct identifier to the following page when transitioning with Link in NextJS

I need to pass an identifier to the next page when a user navigates. On my homepage, I am fetching an array of data and using the map method to display it in a card-based UI. When a user clicks on a card, they should be taken to another page that display ...

Can you please guide me on how I can implement a top AJAX menu like the one on StackOverflow

Have you seen the menu that appears when you first visit a website, with an 'x' on the right to close it? I believe this is done through AJAX - what specific terms should I look up to implement this feature? ...

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:// ...

React Select only enabling single selection at a time

Currently, I am in the process of updating my react app to version 16.8 and also updating all associated libraries. One issue that has come up is with two drop-down selects from Material UI. Since the update, the multi-select option no longer allows multip ...

I encountered an issue with my h3 element's margin not being applied properly when I attempted to add

I'm facing an issue with the margin for <h3> tag in my HTML code. I want to create some space between the form and the h3 element. Here is the CSS: *{ margin: 0; padding: 0; font-family: Arial, Helvetica, sans-serif; } body{ background-ima ...

Determine if a div contains an svg element with JavaScript

My question involves a div containing a question mark and some SVG elements. Here is the initial setup: <div id="mydiv">?</div> When validating a form submission in my code, I check if the div text contains a question mark like this: const f ...

Learn how to effectively showcase various components by leveraging the new react-router-dom v6.0.0 alongside react-redux

My issue is that when I click on a link to render different components, the URL updates but the UI remains unchanged. No matter which item I click on to render, the same thing happens. I've tried numerous solutions to fix this problem without success. ...

inconsistency in button heights

I am currently working on a website project for one of my college courses and I have encountered an issue with the button heights in my slide show not matching up. I'm seeking advice or tips on how to align both buttons to have the same height. Can an ...

Mozilla Extension: Run code on initial launch

Currently in the process of building an add-on and looking to implement specific code for its initial run. What I aim to achieve is clicking on the add-on button, navigating through files, and selecting an executable file. This browsing action should only ...

Import JSON Data into Angular-nvD3 Chart (AngularJS)

I am seeking help to load encoded JSON Data retrieved from a database via queries into an Angular-nvD3 graph. I am unsure about the best approach to achieve this task. The encoded JSON data is fetched using API queries from a database table called PRODUCT ...

What are the steps to employ a query string to display a specific image?

If I understand correctly, I can utilize a query string and parse it to display certain information. How would I apply that concept to load a specific image? https://codepen.io/anon/pen/qYXexG <div id="gallery"> <div id="panel"> <img ...

I am facing difficulties in installing the necessary node modules for my Angular project

After attempting to run npm install, an error message is displayed towards the end: error syscall unlink 22396 error The operation was rejected by your operating system. 22396 error It's possible that the file was already in use (by a text editor or ...

Implementing HTML rendering in a PyQt5 window

As a newcomer to PyQt5 for GUI creation, I could use some assistance. I'm attempting to create a basic window that displays a simple HTML file. However, despite using the code provided below, the window shows up empty. Is there a step I missed in ord ...

Issue with third-party react module (effector) causing Webpack error

UPDATE: After struggling with my own custom Webpack setup, I decided to switch to using react-scripts, and now everything is compiling smoothly. It seems like the issue was indeed with my Webpack/Babel configuration, but I still can't pinpoint the exa ...

How can I create an input field that only reveals something when a specific code is entered?

I am currently developing a website using HTML, and I would like to create an admin section that requires a password input in order to access. After consulting resources on w3schools, I attempted the following code: <button onclick="checkPassword()" i ...

Unveiling the Secrets of Unearthing Data from JSON

My code receives JSON strings through a JSONP call. Although I'm aware of the general JSON structure, I don't know the specific keys and values it will contain. The typical structure is as follows: [ {"key_name": "value"}, {"key_name": ...

Is there a way to incorporate logic into my Angular routes?

I am looking to secure certain routes within 'case' sections based on the dependency of $scope variables (whether forms are valid or not). var loginForm = angular.module('loginForm',[ 'ngRoute', 'stepsControllers&apo ...

Regain focus after selecting a date with Bootstrap datepicker

When initializing a bootstrap datepicker from eternicode with the parameter autoclose: true, there are two undesired behaviors that occur: After closing the picker, tabbing into the next field causes you to start at the beginning of the document again, w ...

Changing time format from ISO time to short time in JavaScript

I am working on an ajax call that retrieves a time in the format 16:06:59, and I need to convert it to 4:06 PM. var mydate = obj[0].time; The variable mydate contains 16:06:59, but when I try to use it with var date = new Date(), it returns today's ...