Topic: Javascript hide two elements by id on onclick of the botton
demzl25 priority asked 2 years ago
Hi,
How you can hide two elements by id on onclick of the botton with Javascript?
Thanks,
Damjan
Mateusz Lazaru staff answered 2 years ago
hi,
in HTML code you've created button
and connected it with JS function fun()
.
When fun()
is called, selected divs get CSS display
property equal to none
, which means they will not be visible, and they will not take any space in your document.
If your point was to make them disapear, it works perfectly fine.
Next time consider connecting buttons with functions in JS code by addEventListener to your button. This approach will work exactly the same, but it will help you to keep your code cleaner.
demzl25 priority commented 2 years ago
Thanks,
Is this example what you have in mind?
https://mdbootstrap.com/snippets/standard/demzl25/4036965#js-tab-view
Grzegorz Bujański staff commented 2 years ago
yes, that was exactly this
demzl25 priority commented 2 years ago
Thank you for your help, I have learned a lot form this.
Damjan
Mateusz Lazaru staff answered 2 years ago
Hi,
There are 2 good ways to do it in JS
btn.addEventListener('click', () => {
document.getElementById('#firstElementId').style.display = 'none';
document.getElementById('#secElementId').style.display = 'none';
});
or
btn.addEventListener('click', () => {
document.getElementById('#firstElementId').style.visibility = 'hidden';
document.getElementById('#secElementId').style.visibility = 'hidden';
});
Here is explained difference between those two attempts.
For some of our components we've provided hide method, for example: myAlert.hide().
demzl25 priority commented 2 years ago
Great thanks,
Damjan
demzl25 priority commented 2 years ago
I m not sure how to connect this js code with specific botton (what js code I need to add to botton) so that two elements on id will close on one botton click?
I have here example:
onclick="HideDiv()"
function HideDiv() { document.getElementById('#firstElementId').style.display = 'none'; document.getElementById('#secElementId').style.display = 'none'; }
Will this work?
Thanks,
Damjan
Mateusz Lazaru staff commented 2 years ago
You need to select button and add event listener to it.Here is complete example.
https://mdbootstrap.com/snippets/standard/mlazaru/3993037
demzl25 priority commented 2 years ago
Great thanks,
Damjan
demzl25 priority commented 2 years ago
Hi,
I'm not able to understand how to get this working.
I have created code snippet with example but I m not sure if it works correctly:
https://mdbootstrap.com/snippets/standard/demzl25/4028711#html-tab-view
Thanks,
Damjan
FREE CONSULTATION
Hire our experts to build a dedicated project. We'll analyze your business requirements, for free.
Answered
- ForumUser: Priority
- Premium support: Yes
- Technology: MDB Standard
- MDB Version: MDB5 4.1.0
- Device: Pc
- Browser: Chrome 97.0.4692.99
- OS: Windows 10
- Provided sample code: No
- Provided link: No