Printable Version of Topic

Click here to view this topic in its original format

HTMLHelp Forums _ Client-side Scripting _ How can I add two Javascript on html?

Posted by: Alexf Aug 2 2020, 12:42 PM

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????

Posted by: Christian J Aug 2 2020, 01:38 PM

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.

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)