I am using the following code form w3schools that uses a button to toggle text:
function myFunction() {
var x = document.getElementById("myDIV");
if (x.style.display === "none") {
x.style.display = "block";
} else {
x.style.display = "none";
}
}
<button onclick="myFunction()">Try it</button>
<div id="myDIV">
This is my DIV element.
</div>
Now, I want to have a page with many buttons that toggle different texts (every button corresponds to a unique text). Of course, I can make it work by copying the function each time I create a new text; myFunction1 <-> myDIV1, myFunction2 <-> myDIV2 etc.
But is there a smarter way to do it? I am thinking it can be done with a single function that select id’s in a specific form but I don’t know how.
3
Answers
Since you are learning JavaScript, I suggest learning to not use some traditionally bad habits.
One thing that is generally more hassle than it’s worth are inline click handlers. Meaning
onclick='myfunction()'
on your elements. Instead usingaddEventListener
offers more capabilities.Also, another cool thing to learn is toggling a CSS class on your elements instead of changing the style directly in JavaScript.
So for my answer I actually add a click handler to the body. Then when you click I check to see if the element you clicked has a specific class. I gave your buttons a class of btnToggle.
Next on each button I use data attributes to dictate what that button should target. This is done by using
data-target="#divID"
.Now in the click handler, I get that target by getting the clicked element and
data.target
.Now I use a CSS class called active that sets display to display.
Then I simply use the clicked element’s class list to toggle that class.
First, let me say that W3Schools is well-known to have incomplete, out of date, or just plain wrong information. You should stay as far away from it as a learning resource as possible. Instead, the Mozilla Developer Network (who are the stewards of the JavaScript language) has what is widely considered to be the authoritative source for learning and documentation on many web technologies and languages.
As to your question (and because you got the code from W3Schools) we have to back up a bit.
year old approach that we used before we had any standardized ways of
doing things. This technique still works for legacy reasons, but
should not be used today.
style
property isdiscouraged. This causes what is called an inline style to be added
to the element and inline styles lead to duplication of code and
difficulty in overriding those styles when that is invariably needed.
id
‘s on elements is a very easy way to access portionsof your page and work with them, but it is also discouraged because
id
based scripting leads to brittle code that doesn’t scale well.The use of
id
‘s should also be avoided in favor of other ways(i.e., location of an element in relation to other elements).
With all that said, the better approach here would be to have your several buttons to press, but have them each just populate one common output element when they are clicked. This way, you don’t need to know about any
id
.See comments inline below:
To try and tie together mine and Keith’s comments – re grouping and event delegation – depending on how your page is arranged you can get away with a more simplified HTML markup, and JS code.
For example, let’s say you have a series of sections, and each section has a paragraph and corresponding button immediately below it. Using event delegation you can add one listener to the containing element (in this case
.container
), and have that catch all of the events from its child elements as they "bubble up" the DOM.The listener’s handler would first check to see if the element that fired the event
matches
a button element, and it would then grab that button’spreviousElementSibling
(the paragraph element). Using CSS andclassList
‘stoggle
method, you can then toggle that text on/off, or to a different colour, etc. This example fades it in/out.