Reputation: 13135
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 taps 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 where to call this from the HTML, or if this is even the right way to go about this. Advice?
Upvotes: 4
Views: 15528
Reputation: 4718
Everyone here provided pretty good insight on different solutions for you to handle your script, but I don't think that anyone stopped to think SHOULD they help improve your script. "or if this is even the right way to go about this ", the answer is no. And perhaps I'm over-simplifying, but with JQM if you're trying to have a div (or any DOM element for that matter) open a new page simply wrap an anchor tag around around it (or in it, whichever is appropriate) and set your href to href="#myNewPage"
and the id on the JQM page that you want to load to id="myNewPage"
jQuery Mobile's frame work is set up to automatically inject JS & AJAX into normal HTML elements to provide a smooth UX. While binding a touch event is sometime needed, this situation doesn't warrant that level of code...thats the beauty of jQuery Mobile =).
Examples of when to bind a touch event: show/hide a dom object, trigger a click for a plug-in etc.
Upvotes: 1
Reputation: 76003
You want to call that function on the pageinit
event for the page on which it resides. You could use some other page-events from jQuery Mobile like: pagecreate
, pageshow
, etc. but I think pageinit
is your best-bet.
The implementation would 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
with the ID of the data-role="page"
element in which your div resides.
This method is preferred over event delegation for the #myDiv
element because binding directly to an element creates less overhead when the event is triggered. If you use event delegation then the event has to bubble-up to the delegation root.
Upvotes: 0
Reputation: 11865
Try
$("#myDiv").live("tap", function(event){
alert('binding');
});
You can place this in side your onReady
javascript file
EDIT:
Upvotes: 1