JQuery Mobile Taphold

I have been trying all day to test a dead simple function in my project. Recipe

  • User deletes and holds list item
  • alert() will appear.

My markup

 ... <body> <ul> <li class="item ...">Hello, I'm an item</li> ... </ul> </body> <script src="jquery.js"></script> <script src="jquery.mobile.js"></script> ... 

My script is

 $('.item').on("taphold", function() { alert("hello"); }); 

I am testing iPad 2 using Safari ... My concern is that jQuery mobile is deprecated because the click() event works fine. I included the source from http//jquerymobile.com , this also did not work.

Thanks!

+4
source share
1 answer

I think the problem is that elements with the .item class .item not exist in the DOM while loading your script. Place the script at the end of your page or attach an event handler to the document element using $(document).on('taphold', 'li.item', function(){

I created the working examples below.

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Taphold event demo</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css"> <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> </head> <body> <div id="tap-page" data-role="page"> <div data-role="header"> <h1>Long-press (taphold) a list item</h1> </div> <div data-role="content"> <ul data-role="listview"> <li class="item">Hello, I'm an item</li> <li class="item">Hello, I'm another item</li> </ul> </div> </div> <script> $(function(){ $('li.item').bind( 'taphold', tapholdHandler ); function tapholdHandler( event ){ alert('Hello'); } }); </script> </body> </html> 

and an example that attaches an event handler to the document element:

 <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Taphold event demo</title> <link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css"> <script src="http://code.jquery.com/jquery-1.10.0.min.js"></script> <script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script> <script> $(document).on( 'taphold', 'li.item', tapholdHandler ); function tapholdHandler( event ){ alert('Hello'); } </script> </head> <body> <div id="tap-page" data-role="page"> <div data-role="header"> <h1>Long-press (taphold) a list item</h1> </div> <div data-role="content"> <ul data-role="listview"> <li class="item">Hello, I'm an item</li> <li class="item">Hello, I'm another item</li> </ul> </div> </div> </body> </html> 
+2
source

Source: https://habr.com/ru/post/1487629/


All Articles