In my javascript (ES6), I have a simple <a>
tag with an event handler, basically when the <a>
tag is clicked I want the page to redirect.
My problem is that when I pass the URL parameter to the function that handles the redirect, the test function executes regardless of whether the addEventListener
has been clicked or not, so it's basically just redirecting back and forth on its own on page load which is not what I want.
Is there any reason this.elem.addEventListener('click', this.test(this.elem.id), false);
is executing on its own?
index.html:
<a id="about" class="a-tag" target='_blank'>About</a>
about.html:
<a id="index" class="a-tag" target='_blank'>Index</a>
Master.js:
import { Nav } from 'module/Nav';
(function() {
Nav.init();
})();
Nav.js:
export const Nav = {
elem: document.querySelector('.a-tag'),
init() {
this.render();
},
test(page) {
window.location.href = "/" + page + ".html";
},
render() {
if (this.elem) {
this.elem.addEventListener('click', this.test(this.elem.id), false);
}
}
};