The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

 
Reply to this topicStart new topic
> How can I add two Javascript on html?, Question
Alexf
post 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????
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Aug 2 2020, 01:38 PM
Post #2


.
********

Group: WDG Moderators
Posts: 8,586
Joined: 10-August 06
Member No.: 7



QUOTE(Alexf @ Aug 2 2020, 07:42 PM) *

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.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

Reply to this topicStart new topic
2 User(s) are reading this topic (2 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 26th October 2020 - 08:43 AM