I have a sample code that tries to color the target when I clicked its designated hyperlinks.
I am making some project and have same function on this one. When I clicked the target, I expected to color the elements that I have been linked to, and in the code it is working, but I'd like to remove the color of the target when I clicked again anywhere else in the screen.
p:target {
background-color: gold;
}
/* Add a pseudo-element inside the target element */
p:target::before {
font: 70% sans-serif;
content: "►";
color: limegreen;
margin-right: 0.25em;
}
/* Style italic elements within the target element */
p:target i {
color: red;
}
<h3>Table of Contents</h3>
<ol>
<li><a href="#p1">Jump to the first paragraph!</a></li>
<li><a href="#p2">Jump to the second paragraph!</a></li>
<li>
<a href="#nowhere">
This link goes nowhere, because the target doesn't exist.
</a>
</li>
</ol>
<h3>My Fun Article</h3>
<p id="p1">
You can target <i>this paragraph</i> using a URL fragment. Click on the link above to try out!
</p>
<p id="p2">
This is <i>another paragraph</i>, also accessible from the links above. Isn't that delightful?
</p>
I'd like to remove the color of the target when I clicked anywhere in the screen. How should I do that?
You may need a little bit of Javascript here:
// Get the target element that you want to remove the color from
const target = document.querySelector('#my-target');
// Add a click event listener to the entire document
document.addEventListener('click', () => {
// When the document is clicked, remove the color from the target element
target.style.color = '';
});