-1

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);
    }
  }

};
daniel aagentah
  • 1,672
  • 5
  • 29
  • 56

1 Answers1

2

Because you don't pass the reference of the function, but the result of the function. You call function which redirects directly. Replace with this

this.elem.addEventListener('click', () => this.test(this.elem.id), false);
Suren Srapyan
  • 66,568
  • 14
  • 114
  • 112