and this CSS: #myDiv{ background:url('../images/so...">

Jquery (mobile) - bind a tap event to a div

If I have this html:

<div id="myDiv"></div> 

and this CSS:

 #myDiv{ background:url('../images/someImage.png') no-repeat; background-size:100%; width:44px; height:44px; } 

I need to open a new page when the user clicks on myDiv. I have an external js file where I have this:

 function bindMyDiv(){ $("#myDiv").bind('tap',function(event, ui){ alert("binding"); }) } 

But I don’t understand how to call it from HTML, or if this is even the right way to get around this. Advice?

+4
source share
3 answers

Try

 $("#myDiv").live("tap", function(event){ alert('binding'); }); 

You can put this in the direction of your javascript onReady file

EDIT:

http://jsfiddle.net/R9e6u/

+1
source

Everyone here provided some good information about the various solutions for processing your script, but I don’t think anyone has stopped to think SHOULD help them improve your script. "or even if this is the right way to do this," the answer is no. And maybe I'm too simplistic, but with JQM, if you are trying to create a div (or any DOM element, for that matter), open a new page, just wrap an anchor tag around it (or in it, depending on what fits) and set href to href="#myNewPage" and the identifier on the JQM page you want to download to id="myNewPage"

jQuery Mobile frame work is configured to automatically add JS and AJAX to regular HTML elements to ensure smooth UX. Although a touch event binding will be needed sometime, this situation does not guarantee that the code level ... is the beauty of jQuery Mobile =).

Examples of binding touch events: show / hide the dom object, trigger a click for a plug-in, etc.

+1
source

You want to call this function in the pageinit event for the page on which it is located. You can use some other page events from jQuery Mobile, for example: pagecreate , pageshow etc., but I think pageinit is your best bet.

The implementation will look something like this:

 $(document).delegate('#page-id', 'pageinit', function () { $("#myDiv").bind('tap',function(event, ui){ alert("binding"); }) }); 

OR

 $(document).delegate('#page-id', 'pageinit', bindMyDiv); 

You would replace #page-id identifier of the data-role="page" element that your div is in.

This method is preferable to event delegation for the #myDiv element, because binding directly to the element creates less overhead when the event fires. If you are using delegation delegation, then the event should go to the root of delegation.

0
source

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


All Articles