Toggle function not working properly in JavaScript

alex_foster_028d89571434b

Alex Foster

Posted on October 12, 2024

Toggle function not working properly in JavaScript

Hi dev.to community!
I’m building a page on WordPress, and I’m trying to toggle the visibility of a table when a button is clicked. The table should appear or disappear depending on its current state. It works, but only after the first click—it doesn’t display correctly the first time I click it.
Here’s the JS code I’m using:

const ticketComparisonBtn = document.getElementById('ticketComparison');
const comparisonTable = document.getElementById('comparisonTable');

ticketComparisonBtn.addEventListener('click', function() {
if (comparisonTable.style.display === 'none') {
comparisonTable.style.display = 'block';
} else {
comparisonTable.style.display = 'none';
}
});

The table is initially hidden with CSS:
.hidden {
display: none;
}
On the first click, the table doesn’t appear, but on the second click, it works as expected. I think it’s a problem with how I’m checking the initial display state. What would be a better approach to make sure it toggles correctly on the first click?
Appreciate any suggestions!

💖 💪 🙅 🚩
alex_foster_028d89571434b
Alex Foster

Posted on October 12, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related