You can't click on something that's not visible. Instead of visibility
use opacity
.
Additionally, don't use inline styles. Just make a CSS class and add/remove it as needed using the .classList
API.
Lastly, this document.getElementsByTagName("span")[0]
is really, really bad code.
// Use .querySelector() and .querySelectorAll() to get elements and collections
// of elements when necessary.
// Set up your event on a parent of all the elements that need the
// same event handler. When a descendant within the parent fires
// an event, that event will bubble up to the parent and be handled
// there. This is called "event delegation"
document.addEventListener("click", toggle);
function toggle(event){
// Check to see if the event was triggered by an element
// that you care about. event.target represents the element
// that actually triggered the event
if(event.target.classList.contains("hideable")){
// Just toggle (or add depending on what you want) the use of the CSS class
//event.target.classList.add("hidden");
event.target.classList.toggle("hidden");
}
}
/* Use CSS classes whenever possible.
They are easier to set up and manage. */
.hidden { opacity:0; }
.hideable { cursor:pointer; }
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<span>My name is: </span>
<span class="hideable hidden">Scott. </span>
<span> I am fine. </span>
<span class="hideable hidden">How are you? </span>
<span> Have a great day! </span>
</body>
</html>