Jerry Lai
Jerry Lai

Reputation: 65

Why does my jquery function only works once?

this may sound stupid but i am a Jquery noob and I am trying to make a div tag to resize when I when swipe left and right on mobile, and I am not sure why its only executed once? can any jquery gurus here help me out !!!! thank you

here is the code

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
  <script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
</head>
<body>

  <div class="box">
  </div>

  <script>
    $(function right(){
      // Bind the swiperightHandler callback function to the swipe event on div.box
      $( "div.box" ).on( "swiperight", swiperightHandler );

      // Callback function references the event target and adds the 'swiperight' class to it
      function swiperightHandler( event ){
        $( event.target ).addClass( "swiperight" );
      }
    });

    $(function left(){
      // Bind the swiperightHandler callback function to the swipe event on div.box
      $( "div.box" ).on( "swipeleft", swiperightHandler );

      // Callback function references the event target and adds the 'swiperight' class to it
      function swiperightHandler( event ){
        $( event.target ).addClass( "swipeleft" );
      }
    });
  </script>
</body>
</html>

Upvotes: -1

Views: 305

Answers (2)

Arun P Johny
Arun P Johny

Reputation: 388436

You need to remove and add the classes

function swiperightHandler( event ){
  $( event.target ).removeClass('swipeleft').addClass( "swiperight" );
}

and

function swiperightHandler( event ){
  $( event.target ).removeClass('swiperight').addClass( "swipeleft" );
}

Upvotes: 1

sync
sync

Reputation: 5640

It probably is being executed more than once, addClass won't do anything when you call it the second time as it's already added that class to the element!

Upvotes: 0

Related Questions