0

I have javascript application building on modules. I am using webpack. I want to add eventlistener to element. But i can't do it. I receive the error "ReferenceError: x is not defined". Where in my app i should place my eventlistener function. It works if i write function inline, but i don't want to do that.

Here is my app.js file (entry point).

import {Main} from "./components/Main";
import './style.css'

export default (function () {
    document.getElementById("app").innerHTML = Main();
}());

Component with element i want to have eventlistener - onclick in element:

import {CompanyContainer} from "./CompanyContainer";

export const UserContainer = user => {
    return (
        `
        <a href="#" onclick="">${user.getFullName()}</a>
        <div class="user-details hide">
            <p>Birthday: ${user.getBirthDay()}</p>
            <p><img src="" width="100px"></p>
            ${CompanyContainer(user.companyId)}
        </div>
        `
        )
};

3 Answers3

1

Quick idea:

const e = document.createElement('div');
e.innerHTML = yourHTMLCode;
e.querySelector('a').addEventListener('click', yourListenerFunction);

Edit: I would rewrite your component in this manner:

import {CompanyContainer} from "./CompanyContainer";

export const UserContainer = (user, onClick) => {
    const html = `
        <a href="#">${user.getFullName()}</a>
        <div class="user-details hide">
            <p>Birthday: ${user.getBirthDay()}</p>
            <p><img src="" width="100px"></p>
            ${CompanyContainer(user.companyId)}
        </div>
        `;
    const element = document.createElement('div');
    element.innerHTML = html;
    element.querySelector('a').addEventListener('click', onClick);
    return element;
};

This way you can pass you listener during container creation.

szatkus
  • 1,292
  • 6
  • 14
0

I edited your code and started a fully functional example at github(https://github.com/lalosh/stackoverflow-webpack-event-listener) you can check it yourself.

notice that you didn't even pass an event handler in your code, but assuming you've passed one like

  function onClickHandler(event){...}

  "<a onclick="onClickHandler(event)"> ....

the onClickHandler won't be called successfully because it's scroped to the file and not to the global object (window)

to fix simply attach the event to the global object window

  window.onClickHandler = function onClickHandler(event){...}

  "<a onclick="onClickHandler(event)"> ....

and note that you can use addEventListener (more preferend)instead of directly attaching the event listener from inside html, I suggest you check the comparison here addEventListener vs onclick

Louay Al-osh
  • 3,177
  • 15
  • 28
0

I decided to rewrite my code and made with document.creatreElement instead of innerHTML. And it works. A little bit more lines of code but works and conceptual right. Thanks for the help.