Stijn Martens Stijn Martens - 1 year ago 107
Javascript Question

iOS Safari: touchstart doesn't fire on dynamically inserted element

I'm working on an web app for iOS Safari.
I've got a search input with an autocompletion/suggestions list below it.
With javascript I add the suggestions to the list:

+= '<span ontouchstart="selector_select(' + i + ');">' + name + '</span><br />';

Now the problem is that the
doesn't seem to get fired when touching the element.

I've tested it with
etc. But nothing happens.

How can I get it to work?

Answer Source

The ontouchstart="" attribute does not add a listener to the node when inserted into the DOM. Only at the first load of the page.

Using addEventListener('touchstart', ...); on the items after inserting them is the solution here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download