harshdeep
harshdeep

Reputation: 1

simple example of gesture in hammerJS

i am trying to run simple gesture code like tap swipe on my browser

<html>
<head>
</script src="https://hammerjs.github.io/dist/hammer.js">
</script>
<script>
    var myElement = document.getElementById('myElement');

    // create a simple instance
    // by default, it only adds horizontal recognizers
    var mc = new Hammer(myElement);

    // listen to events...
    mc.on("panleft panright tap press", function(ev) {
        myElement.textContent = ev.type + " gesture detected.";
    });
</script>


<style type="text/css">
#myElement {
    background: black;
    height: 300px;
    text-align: center;
    font: 30px/300px Helvetica, Arial, sans-serif;
}
</style>


</head>
<body>


    <div id="myElement"></div>

</body>
</html>

i am trying to execute this code but this is showing error Cannot read property 'addEventListener' of null

Upvotes: 0

Views: 2691

Answers (1)

Derek
Derek

Reputation: 1795

As written, the javascript runs before the DOM is ready and it won't find the element to attach to. Try this:

<script>

  document.addEventListener("DOMContentLoaded", function(event) {

    var myElement = document.getElementById('myElement');

    // create a simple instance
    // by default, it only adds horizontal recognizers
    var mc = new Hammer(myElement);

    // listen to events...
    mc.on("panleft panright tap press", function(ev) {
        myElement.textContent = ev.type + " gesture detected.";
    });
  });
</script>  

You can refer to https://developer.mozilla.org/en-US/docs/Web/Events/DOMContentLoaded

The default color of text is black so you won't be able to read the message unless you tweak your css by adding something like color: white;.

<style type="text/css">
#myElement {
  background: black;
  height: 300px;
  text-align: center;
  font: 30px/300px Helvetica, Arial, sans-serif;
  color: white;
}
</style>

Upvotes: 1

Related Questions