Hello, I’d like to inquire how to create multiple hidden/show more coding for my WordPress site. I am having issues with the following code below, the source is getting mixed up. How do I differentiate the two? Please help, thank you!
–Script1–
<script language="javascript">
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "Click here for complete details.";
}
else {
ele.style.display = "block";
text.innerHTML = "Hide details.";
}
}
</script>
<a id="displayText" href="javascript:toggle();">Click here for complete details.</a>
<div id="toggleText" style="display: none">Details</div>
</span>
–Script2–
<script language="javascript">
function toggle() {
var ele = document.getElementById("toggleText");
var text = document.getElementById("displayText");
if(ele.style.display == "block") {
ele.style.display = "none";
text.innerHTML = "Click here for more information.";
}
else {
ele.style.display = "block";
text.innerHTML = "Hide Disclaimer.";
}
}
</script>
<a id="displayText" href="javascript:toggle();">Click here for more information.</a>
<div id="toggleText" style="display: none">Information</div>
</span>
Had another read through the code and I think I see what’s going on, assuming that the two <a> and <div> tags are in the same page. They both have the same id attribute. ID’s should be unique on a page. If you can give them all unique ID’s, I think you’ll get better results.
That should work. It wouldn’t be particularly DRY (don’t repeat yourself), as the same script is being repeated, with just a change of target id, but it should at least get you functional.
Hey @Gothic_Sanctuary, you have two functions there doing the basically same thing – this is terribly inefficient and hard to maintain. You’d only need one if you separated your JS and HTML as @felgall suggested, like
function toggle() {
var ele = this.nextElementSibling;
if (ele.style.display == "block") {
ele.style.display = "none";
this.textContent = 'Anzeigen';
} else {
ele.style.display = "block";
this.textContent = 'Verbergen';
}
}
document.getElementById('displayText1').addEventListener('click', toggle);
document.getElementById('displayText2').addEventListener('click', toggle);
This makes your code much more reusable. (Technically, you could also call that function inline and pass the relevant IDs as parameters, but there are other concerns as noted above.)
And then you could indeed do this entirely w/o JS. :-) Like