How can I add two Javascript on html?, Question |
How can I add two Javascript on html?, Question |
Alexf |
Aug 2 2020, 12:42 PM
Post
#1
|
Group: Members Posts: 2 Joined: 2-August 20 Member No.: 27,470 |
Hey guys, I wanted to create a html that shows the translation and hides the translation. The first one was working but when I copied the first one and created another one, the first one didn't work, just the second one. This is the html:
<script type="text/javascript"> function ShowHideDiv(btnPassport) { var dvPassport = document.getElementById("dvPassport"); dvPassport.style.display = btnPassport.value == "Show Translation" ? "block" : "none"; } </script> <span>Translation</span> <input type="button" value="Show Translation" onclick="ShowHideDiv(this)" /> <input type="button" value="Hide Translation" onclick="ShowHideDiv(this)" /> <div id="dvPassport" style="display: none"> Olá tudo bem? Como vocês estão? My question is how can I make them work when I add another one or more than two???? |
Christian J |
Aug 2 2020, 01:38 PM
Post
#2
|
. Group: WDG Moderators Posts: 9,656 Joined: 10-August 06 Member No.: 7 |
The first one was working but when I copied the first one and created another one, the first one didn't work, just the second one. That's because each ID value must be unique on an HTML page. Instead you can do like this: CODE <script type="text/javascript"> function ShowHideDiv(btnPassport) { var dvPassport = btnPassport.parentNode.getElementsByTagName('div')[0]; // first DIV in the parent container dvPassport.style.display = btnPassport.value == "Show Translation" ? "block" : "none"; } </script> <section> <span>Translation</span> <input type="button" value="Show Translation" onclick="ShowHideDiv(this)" /> <input type="button" value="Hide Translation" onclick="ShowHideDiv(this)" /> <div style="display: none"> Olá tudo bem? Como vocês estão? </div> </section> <section> <span>Translation</span> <input type="button" value="Show Translation" onclick="ShowHideDiv(this)" /> <input type="button" value="Hide Translation" onclick="ShowHideDiv(this)" /> <div style="display: none"> Olá tudo bem? Como vocês estão? </div> </section> I'd consider using more semantically meaningful HTML elements than DIV and SPAN though (like a heading and a P?). Also the translations will be permanently hidden for users with javascript disabled. To avoid that you can hide them with javascript as well, but that requires a little more javascript. |
Lo-Fi Version | Time is now: 25th April 2024 - 01:34 AM |