0

I would like to build in error handling for this piece of javascript so that if #next doesnt exist that it will do something else. Currently when it doesnt exist it just gives me an undefined in the url or an error page. Please let me know what i can do here. thanks

<script>
$(document).on("pageinit",function(){

  var pathname = $(location).attr('href');
  var leva = $('#next').attr("href");
  var prava = $('#prev').attr("href");

  $("body").on("swiperight",function(){
    <!--alert("You swiped right!");-->
    location.href=prava;
  });                       
  $("body").on("swipeleft",function(){
    <!--alert("You swiped left!");-->
    location.href=leva;
  });
});
</script>
4
  • You can check $('#next').length to see if any elements were selected. Or just check if leva is undefined.
    – Chad
    Commented Feb 12, 2014 at 20:54
  • @Chad do you have a recommendation for how to do this?
    – Steven
    Commented Feb 13, 2014 at 2:47
  • 1
    if(leva) { location.href=leva } else { /* do something else */ }
    – Chad
    Commented Feb 13, 2014 at 15:52
  • Thanks @Chad if you want to put it as an answer I can accept it.
    – Steven
    Commented Feb 13, 2014 at 15:53

1 Answer 1

1

You can check $('#next').length to see if any elements were selected. Or just check if leva is undefined.

Something like this:

<script>
$(document).on("pageinit",function(){

  var pathname = $(location).attr('href');
  var leva = $('#next').attr("href");
  var prava = $('#prev').attr("href");

  $("body").on("swiperight",function(){
    <!--alert("You swiped right!");-->
    location.href=prava;
  });                       
  $("body").on("swipeleft",function(){
    <!--alert("You swiped left!");-->
    if(leva) {
      location.href=leva;
    } else {
      // Some other action
    }
  });
});
</script>

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.