Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

empty event listener: Is this ok?

Some Quick Background

I'm building an iOS app that uses html web views in some areas. I wanted to make sure the html buttons on those pages looked and felt as much like iOS buttons as possible. To accomplish this, I wanted a tap state so the html button depressed when tapped. Now in HTML this is easy. You just set a style for :active or :hover or whatever. I actually had this defined already. In iOS, however, those states don't engage on tap – at least normally. So my goal was to write a little script that added a class to the button to change its appearance ontouchstart.

The Issue

However, it turns out I didn't need to get that complicated...by pure accident I ran a test with the following code:

document.addEventListener('touchstart', function(event) {
    console.log("test");
}, true);

I'm pretty green with javascript & jQuery, so all I intended on doing was checking my syntax and making sure the eventListener fired when I tapped the button. To my surprise, the button's :active states in the css fired (as well as the :hover states). That code...solved my problem!

My Question

So here's my question: Is the above code valid? I mean, is it bad to do this? It's as if the empty eventListener just triggered behavior that desktop browsers already offer. Is there anything wrong with using this method? I'm green, but I don't want to pick up bad habits. If this is a bad way to code I don't want to use it.

Thanks for any insight you guys can give me into this!

like image 320
David Vasquez Avatar asked Nov 13 '22 21:11

David Vasquez


1 Answers

I personally don't think anything's wrong with empty event listeners (save for the overhead of a function call --- which sounds negligible here anyway). I'd suggest you leverage jQuery's noop function though if you must add an event listener but have it do nothing:

$(document).on('touchstart', $.noop);

// or

document.addEventListener('touchstart', $.noop);
like image 118
Richard Neil Ilagan Avatar answered Nov 15 '22 11:11

Richard Neil Ilagan