Nick Thakkar
Nick Thakkar

Reputation: 892

Window.click event does not fire on IOS safari - JavaScript only

Vanilla javascript -

document.addEventListener("click", function(){ alert('click fired');});

with angular 2 + -

 @HostListener('window: click', ['$event'])
        public iosSafariClick(e: any): void {
         alert('event fired');
        }

None of this method worked on IOS safari on iPad.

Unless I click some button, hyperlink, or any actionable item, Click event is not fired.

My goal is to fire blur event on a 'div element'.

To do so I am trying to check if the any click event fired on HTML body and check if it was on not the 'div element'.

HTML >

<html>
  <body>
    <div id= 'menu'>123...</div>
  </body>
</html>

Angular Component > typescript >

 @HostListener('window: click', ['$event'])
   public iosSafariClick(e: any): void {
     if(e.target.id !== 'menu'){
       this.menu = false;  // to close menu 
     }        
   }

Is there any way using javascript or angular to overcome this hurdle?

Upvotes: 7

Views: 8364

Answers (2)

bresson
bresson

Reputation: 901

I've forgotten more about Angular than I remember but I ran into this same problem when click was mapped to 'window.' Switch the listener from 'window' to 'body' fixed the issue in Safari.

Good listener

document.querySelector('body').addEventListener('click', e => {
  console.log('clicked ', e)
// oh yeah, I'm good!
})

Bad listener

window.addEventListener('click', e => {
  console.log('clicked ', e)
// oh yeah, I'm good!
})

Upvotes: 7

Nico
Nico

Reputation: 2021

When using touch based devices, the events issued to the browsers are different. It also gives the developer accurate use cases, to design and develop around.

I would assume that since there is no mouse then there will be no click event.

Taken from MDN: In order to provide quality support for touch-based user interfaces, touch events offer the ability to interpret finger (or stylus) activity on touch screens or trackpads.

Try using: document.addEventListener('touchstart', () => console.log('touch called'));

You can always opt to using function () {} instead of () => {}

See full details: https://developer.mozilla.org/en/docs/Web/API/Touch_events

Upvotes: 6

Related Questions