1

I'm using the Hammer.js library (http://hammerjs.github.io/) to enable touch gestures in a vanilla javascript environment. After including the library, I have a call that works on my gallery pages. The call fails should the id slide not be found on the page. The resulting TypeError also prevents the other js for the site from being executed. I'm really new to this, but from doing some reading I think I need to wrap this code in a test so it won't run if id slide does not exist. Knowing how to do this will help me fix some other issues with other ids and libraries.

So after the Hammer.js code I have my own code:

var slide = document.getElementById('slide');
var mc = new Hammer(slide);
mc.on("swipeleft", function(ev) {
var url = document.querySelector('a.next').getAttribute('href');
if (url) {
    window.location = url;
}
});

mc.on("swiperight", function(ev) {
var url = document.querySelector('a.prev').getAttribute('href');
if (url) {
    window.location = url;
}
});

How do I prevent this code from executing if the page doesn't contain the id slide? (and when I say it doesn't contain it, I mean that it will not exist on that page, not that the DOM isn't ready.)

Thanks.

2 Answers 2

2

Just test for it:

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

if( slide ){
  // .. your code
}
1
  • Worked like a charm. Thanks.
    – Ian
    Commented Feb 2, 2017 at 23:35
1

End the surrounding function execution if slide is falsy:

var slide = document.getElementById('slide');    
if (!slide) return;
//... The rest of your code
2
  • This works, but only if there's no other code below that should still run Commented Feb 3, 2017 at 16:05
  • 1
    Yeah absolutely, I tend to prefer this style over nesting code inside if statements (especially if there are several checks). In the context of this example though the difference is trivial, I'd probably even do it your way. Commented Feb 3, 2017 at 16:23

Not the answer you're looking for? Browse other questions tagged or ask your own question.