Beginning with JavaScript, I wrote a little script that adds a class to an element on click, and then removes this class if, and only if, another element is click.
I am trying to respect DRY, so I know I should write a function instead to avoid repeating the code such as :
function ToggleClass(element) {
if (FacebookConst.classList.contains("link-ranking-active") || GoogleConst.classList.contains("link-ranking-active") || ComparisonConst.classList.contains("link-ranking-active") {
//remove "link-ranking-active" class to all constants **BUT** of element
};
};
but I don’t know the syntax.
Here is my code:
const GoogleConst = document.getElementById('Google');
const FacebookConst = document.getElementById('Facebook');
const ComparisonConst = document.getElementById('Comparison');
const Page = document.getElementById("result");
GoogleConst.addEventListener("click", e => {
GoogleConst.classList.add("link-ranking-active");
if (FacebookConst.classList.contains("link-ranking-active") || ComparisonConst.classList.contains("link-ranking-active")) {
FacebookConst.classList.remove("link-ranking-active");
ComparisonConst.classList.remove("link-ranking-active");
};
});
FacebookConst.addEventListener("click", e => {
FacebookConst.classList.add("link-ranking-active");
if (GoogleConst.classList.contains("link-ranking-active") || ComparisonConst.classList.contains("link-ranking-active")) {
GoogleConst.classList.remove("link-ranking-active");
ComparisonConst.classList.remove("link-ranking-active");
};
});
ComparisonConst.addEventListener("click", e => {
ComparisonConst.classList.add("link-ranking-active");
if (FacebookConst.classList.contains("link-ranking-active") || GoogleConst.classList.contains("link-ranking-active")) {
FacebookConst.classList.remove("link-ranking-active");
GoogleConst.classList.remove("link-ranking-active");
};
});
.link-ranking-active{
box-sizing: border-box;
position:relative;
padding: 0.3em;
height: 100%;
width: 100%;
border-radius: 0.3em;
border: 0.15em solid #48ffd5;
}
<div class="page">
<div class="ranking" id="ranking">
<ul class="ul-menu">
<li class="li-menu"><a class="link-ranking" id="Google" href="#key">Google</a></li>
<li class="li-menu"><a class="link-ranking" id="Facebook" href="#key">Facebook</a></li>
<li class="li-menu"><a class="link-ranking" id="Comparison" href="#key">Comparison</a></li>
</ul>
</div>
</div>