I made web component like below.
Webtest.js
class Webtest extends HTMLElement {
constructor() {
super();
}
connectedCallback() {
this.attachShadow({mode: 'open'});
this.shadowRoot.innerHTML = `
<style>
.special {
color: green; /* Active link styling */
font-weight: bold;
}
</style>
<a id="testId" href="/mypath/index.html">textA</a>
<a id="testId" href="/mypath/subfolderA/subfolderA.html">textB</a>
<a id="testId" href="/mypath/subfolderB/subfolderB.html">textC</a>
<a id="testId" href="/mypath/subfolderC/subfolderC.html">textD</a>
`;
const links = this.shadowRoot.querySelectorAll("#testId");
links.forEach(link => {
link.addEventListener('click', () => {
this.shadowRoot.querySelector('.special')?.classList.remove('special');
link.classList.add('special');
});
});
}
}
customElements.define('webtest-component', Webtest);
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="dark">
<script src="./Webtest.js"></script>
</head>
<body>
<webtest-component></webtest-component>
</body>
</html>
I have 4 hyperlinks on top of page like this.
enter image description here
I want to highlight the text of last clicked link (one of textA, textB, textC, textD) by inserting special class to last clicked link. But it does not work.
What I tried:
Use ‘addEventListener’ to get the click effect.
click effect:
- Remove ‘special’ class from last clicked one.
- Add ‘speical’ class to last clicked one.
- Since ‘special’ class is defined in style section, it should be highlighted.
Expecting result:
After clicking each text, each text should be highlighted as green color and bold.
Thank you for your help!
According to Nick and Bravo’s help, this is what’s happening. (Thank you very much!)
After clicking page, class properly gets updated but the page redirects to another page and gets refreshed.
So the updated class by the JS only lasts momentarily before the page refreshes.
I want to navigate to each page AND highlight the text of last clicked link.
I want to keep my format as it is.
Any suggestions would be really appriciated!
If you think it is not possible, kindly share as well!
Thank you.