addEventListener on <button> vs <a> (link)

Why works the EventHandler on a button but not on an a-Tag.
Here are an example:

var
  el: TJSHTMLElement;
begin
  // This works
  // HTML = '<button id="mytest" type="button">mytest</button>'
  el := document.getHTMLElementById( 'mytest');
  if el <> nil then
    el.addEventListener( 'click', @myTest);

  // This works NOT
  // HTML = '<a id="mytest2" href="#">mytest2</a>'
  el := document.getHTMLElementById( 'mytest2');
  if el <> nil then
    el.addEventListener( 'click', @myTest2);

There is no error when assigning the event.
el.addEventListener works without an error
But the event is never called

I have no visible components here in the form. Elements are in the DOM.

And can I do anything about it?

I cannot see a problem.
See attached test project.
Project1.zip (5.5 KB)

Yes, your test works.

I need to investigate where the differences are for me.

I have now done many different tests.
The test program (also heavily modified) works.
Our real program, however, does not. Until I have a solution, I will design the (dynamically created) link as a button. We can make it visually identical to the link.

If anyone has any idea where the origin of this problem might lie, I would be very grateful.
We are already very deep into development and are doing a lot of non-visual work (without components, dynamically generated HTML code) and are using JavaScript directly.

Thank you

The problem was found after a few hours.
It had nothing to do with <a> or <button>. Maybe something to do with the timing.

Several DIV containers were dynamically created, each containing a link for editing and deleting.

These containers were assigned to the parent using "innerHTML".
This meant that everything worked for one container. With 2 containers, only the second worked. With 5 containers, sometimes the last two or the last three worked.

In my "Add" function, I no longer worked directly using innerHTML, but created an additional container using createHTMLElement('DIV'). I assigned my dynamic HTML code to this using innerHTML.
Then I inserted the additional DIV using ParentElement.append( ).
Then I added the addEventListener as described above.

Now everything works.

For everyone who occasionally creates HTML dynamically. Often it is enough to simply describe innerHTML. However, if problems occur, it is always better to use the available functions for creating and setting properties.

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.