Search code examples
javascriptmobilehammer.js

basic touch gesture not working, using hammer.js


Im just beginning to learn javascript so I can implement touch gestures, I am using the hammer.js library, but even a simple piece of code doesnt seem to work, does anyone know if Im missing something obvious?

I am including hammer.js correctly (have tested it by putting in the path in the browser) And I have included this code in the head...

<script type="text/javascript">
    var element = document.getElementById('tapdiv');
    var hammertime = Hammer(element).on("tap", function(event) {
    alert('hello!');
    });
</script>

and my html...

<div id="tapdiv">
 <img src="files/tabdiv.jpg" />
</div>

EDIT: IM also receiving this error in the console for hammer.js ...

TypeError: el is null [Break On This Error]

if(!css_props || !el.style) {


Solution

  • It appears that your javascript is attempting to access an object in the DOM that doesn't exist yet -- make sure you execute your javascript after the DOM is ready:

    <script type="text/javascript">
    window.addEventListener('load', function() { 
        var element = document.getElementById('tapdiv');
        var hammertime = Hammer(element).on("tap", function(event) {
            alert('hello!');
        })
    
    }, false);
    </script>