I created a codepen showing what I need done about 3 times in a page. I used the actual “ID” name though; long form.
The first thing I want to happen is the text to be hidden or displayed. The text on the button is an addition I added later.
I will have 3 sections within the same page with a button displaying “Show” or “Hide” and some text will be hidden or displayed. I tried to write the actual function to use any ID and it failed. It works when I actually use the
div>’s id that contains the text to be hidden.
Note: I am for the most part following an example in my course notes on how to write this.
This is what I tried without the button text:
var e = document.getElementById(id);
e.style.visibility = “none”;
Does your code keep the same space when hidden? I wanted the text to push down when it displays and then removes the space when it is hidden. In my example, the button moves back up to the paragraph when the other paragraphs get hidden again.
Thank you very much with your help.
I have not used “addEventListener” very much yet and whenever I see the “el”, I forget what it means.
I would like to confirm one thing. I have 3 buttons on one page. Each button hides/shows their own paragraph. Is it correct that I place an “addEventListener” for each one? This is what I did and it works. But, am I writing this long form again? Is there a shorter way? What happens if you have many buttons (not that you would probably)?
This is what I did:
var txt = document.getElementById(“toggleMe1”);
var txt2 = document.getElementById(“toggleMe2”);
btn = document.getElementById(“showHide1”);
btn2 = document.getElementById(“showHide2”);
//function to toggle text
if (el.innerHTML === “Show”)
el.innerHTML = “Hide”;
el.innerHTML = “Show”;
It works. When I click the first button, its paragraph that was hidden, displays. The second paragraph stays hidden. When I click the second button, its paragraph displays and the first paragraph stays as I left it.
When I see the code written and I go through it, I understand it (eventually); but, when I try to write it on my own, often I struggle with it and need help. I never programmed before this course and now I know why.