I have a div that I want hidden on page load. The class name on the div is "messages-hide"
When I click on a submit button, I want to change the class on that div to "messages-show".
My HTML is:
<div class="messages-hide"></div>
<input type="submit" id="btnSubmit" value="Send the request" />
My CSS is:
.messages-hide {
display: none;
}
.messages-show {
display: block;
}
The submit button works as is, but it’s not changing the class (obviously).
I’m assuming this is fairly simple using Javascript or jQuery, but I don’t know where to begin.
I’ve found several solutions that look like they should work, but nothing that works specifically with an input/submit button. I’ve already spent hours on this. Figure it’s time to ask for help…
I’m open to anything that will work.
Any help will be greatly appreciated… thanks!
2
Answers
There are multiple ways to do this.
The simplest way in my opinion is have a default class lets call it
messages
. And in that class is display none.Then have a class called
show
that is display block.Then on click of your button simply add the show class to the messages div.
However, one note is if its a submit button in a form, once the form reloads the page the messages will be hidden again. Unless you have more going on in your javascript submit/click function that you haven’t posted.
Update
If you want to show the messages div after page load, then you can use localStorage.getItem and localStorage.setItem.
Due to the limitations in the snippet tool, I can’t enable localStorage. But for your implementation, just uncomment those lines.
You can use JavaScript to handle the click event of the submit button and change the class name of the div with the class "messages-hide" to "messages-show". Make sure to add some CSS to control the visibility of the div based on its class.
Here’s a full example:
HTML:
JavaScript (script.js):
This code will switch the class of the div from "messages-hide" to "messages-show" when the submit button is clicked, and your message will become visible if it’s hidden. Make sure the CSS is set up to hide the "messages-hide" class and show the "messages-show" class as demonstrated above.
You can also use a toggle-like behavior to show and hide the div on successive clicks of the submit button. You can achieve this by checking the current class and then changing it accordingly.
Here’s the updated JavaScript code: