Seeking some guidance as a newbie here on how to deal with a problem I'm currently tackling. I understand that using an object constructor may not be the most efficient way to handle this, but I'm eager to enhance my knowledge of objects. My query revolves around finding something akin to this.function that can refer to all other objects that did not initiate my function. Here is the goal I aim to achieve:
<!doctype HTML>
<html>
<head>
<title>Test</title>
<style type="text/css">
a {
text-decoration: none;
color: black;
}
a:visited {
text-decoration: none;
color: black;
}
</style>
</head>
<body>
<ul>
<li><a href="#" id="one"> Test</a> </li>
<li><a href="#" id="two"> Test again</a> </li>
<li><a href="#" id="three">Tester </a></li>
<li><a href="#" id="four"> Testify</a> </li>
</ul>
<script>
var first = document.getElementById('one');
var second = document.getElementById('two');
var third = document.getElementById('three');
var fourth = document.getElementById('four');
var colorChange = function(theID) {
this.id = theID;
this.formatContent = () => {
this.id.style.color = "red";
};
}
test = new colorChange(first);
testAgain = new colorChange(second);
tester = new colorChange(third);
testify = new colorChange(fourth);
function createEventListeners() {
if (first.addEventListener) {
first.addEventListener("click", test.formatContent, false);
}
if (second.addEventListener) {
second.addEventListener("click", testAgain.formatContent, false);
}
if (third.addEventListener) {
third.addEventListener("click", tester.formatContent, false);
}
if (fourth.addEventListener) {
fourth.addEventListener("click", testify.formatContent, false);
}
}
function init() {
createEventListeners();
}
if (window.addEventListener) {
//call init() on page load
console.log("> Adding TC39 Event Listener...");
window.addEventListener("load", init, false);
} else if (window.attachEvent) {
console.log("> Adding MS Event Listener...");
window.attachEvent("onload", init);
}
</script>
</body>
</html>
Upon clicking one of the li items, you'll observe that its color changes to red. However, the issue lies in the fact that this change persists when you click another li item. I thought about instructing the browser to revert all other objects back to black when the formatContent() function is executed. Is there a simple way to achieve this?
Here's a link to a pen for your reference: https://codepen.io/seanbarker182/pen/JexPVz
Thank you in advance for any assistance provided!