1

I have a web-page (front-end in Angular 2), and I attach a simple external javascript script to the HEAD of the index.html.

Now, I want from this external javascript to attach some functions to onclick events to some buttons.

The problem is that, I have many routes to this website and at each route I have different buttons.

The external javascript obviously initializes once on the webpage load, and I can't bind other DOMS that belong to other routes.

For example if I am to route /login, and attach onclick to button with idlogin, and refresh the page then OK the javascript will work.

But if I am at route /login and attach onclick to button register with idregister (which belongs to different route eg /register) and refresh the page then the javascript won't work because the button register doenst belong to this route. And if I change the route to /register then again, the javascript won't work.

So one possible solution would be, upon the load of external javascript to get ALL the DOMS to ALL the whole web-page (from all routes) and then to bind the functions I want.

Can I do that?

Thanks in advance!

EDIT: Mind you that the binding of onclick to some button must happen on the external javascript. I can't write . All the DOM binding must happen dynamically on the script.

Tasos
  • 47
  • 1
  • 6

1 Answers1

2

You need to use event delegation. Here is a simple example about that approach:

   /**
    * Example of DOM event delegation
    * @author: Georgi Naumov
    * gonaumov@gmail.com for contacts and suggestions
    **/
    window.addEventListener('click', function(event) {
        if(event.target && event.target.tagName && event.target.tagName === 'INPUT') {
          console.log('button is clicked');
       }
    }); 

This snippet will execute something for all buttons including buttons that have created in the future. More information you can see here: What is DOM Event delegation? You probably can use some conditions to separate only buttons which you need.

Just bear in the mind:
This is not Angular way. Probably will be better if you have some solution on routing level.

Georgi Naumov
  • 3,890
  • 4
  • 33
  • 50