Your error is caused because when you remove an element from the HTML and then your Javascript tries to refer to that element without proper protections, it causes a script error and the script aborts execution because of the error.
The second thing you need to do when learning Javascript (after learning how to write your first script) is to learn how to check for errors in the debug console in the browser. That will show you when you have execution errors that are aborting your script and they will usually show you what line the error occurs on.
In this case, you would attempt to get a DOM element with a line such as:
var button = document.getElementById("estigmas-trigger");
And, then you would attempt to use the button
variable. But, if the estigmas-trigger
element was not in the page, then button
would be null
and it would be an error to reference a property of null
such as .onclick
.
In addition, your code is horribly repetitive. You really should never copy nearly identical code multiple times into your code. Instead, create a reusable function and use that function multiple places or if your code is almost entirely identical except for one input parameter (which is the case for you), then you can just put the one input parameter into an array and loop through the array.
Here’s a much more DRY implementation (this replaces all of your code):
var buttons = ["obj-trigger", "lineas-trigger", "cultura-trigger",
"igualdad-trigger", "proyectos-trigger", "estigmas-trigger",
"soy-trigger", "tudef-trigger"];
buttons.forEach(function(id) {
var button = document.getElementById(id);
if (button) {
button.addEventListener("click", function(e) {
var cont_id = this.id.replace("trigger", "cont");
var elem = document.getElementById(cont_id);
if (elem) {
var style = elem.style;
if (style.display !== "none") {
style.display = "none";
} else {
style.display = "block";
}
}
});
}
});
Summary of changes:
-
Put all the trigger ID values into an array of strings so you can just loop through each one that you want to apply identical code to.
-
Use
.forEach()
to loop through the array of strings. -
Get the DOM element for each id and check to see if it is present before trying to use it (this will solve your original problem).
-
Use
.addEventListener()
to add the click event handler as this is much more scalable than.onclick
because you can have multiple click handlers for the same element this way. It is a generally good habit to switch to use.addEventListener()
. -
Rather than refer to the
xxx-cont
ids by name, just derive them from thexxx-trigger
ids using a simple text replacement. This saves more duplication and typing in your code. -
Get the
xxx-cont
object in the DOM and also check to see if it exists before attempting to use it (safe coding).
2
solved JavaScript doesn’t work after I remove one