jQTouch
jQTouch copied to clipboard
AJAX and .swipe Functions
With b4rc the swipe() functions (swipe, swipeLeft, swipeRight) do not work on list items that have been added via AJAX. Here's how to reproduce it with the code from the download link:
-
Create demos/main/ajax_test.php with the following content:
<ul class="rounded"> <li><a href="#" id="swipeme">Swipe me!</a></li> </ul>
-
Modify the callbacks div from demos/main/index.html to the following (only adding a swipetest div):
<div id="callbacks"> <div class="toolbar"> <h1>Events</h1> <a class="back" href="#home">Home</a> </div> <div class="scroll"> <ul class="rounded"> <li id="orient">Orientation: <strong>portrait</strong></li> <li><a href="#pageevents" data-custom="WOOT!">Page events</a></li> <li><a href="#" id="swipeme">Swipe me!</a></li> <li><a href="#" id="tapme">Tap me!</a></li> </ul> <div id="swipetest"></div> </div> </div>
-
Add the following javascript code:
var url = 'ajax_test.php'; $.get(url, function(data) { $('#swipetest').html(data).show(); },'html');
-
Now when you test, you will see the swipeme loaded from AJAX does not trigger the swipe function.
Looks like it may not be isolated to only swipe functions, but tap functions are affected as well.
This is a crude work around, but I found that pulling the swipe assignment out into its own function and calling it with a setTimeout with a couple second delay gives the DOM time to load and then it works. Maybe this workaround can help the developer(s) diagnose the issue and fix it permanently, but for now..
setTimeout("_attachSwipes($id)",500); // where $id is the id of the element to add the swipe handler too
I am going to spend a few minutes modifying this a bit so it will check for the DOM to load and then execute rather than hardcoding the timeout. I found that checking for one of the element's attributes comes back undefined before it exists in the DOM so I am just going to have it loop every half second or something and once it exists, attach the action.
That was a tricky one!
For the helpless, here's my bit that I came up with finally to address it,
When I want to attach the swipe, I would just call attachSwipes(obj_id)
function attachSwipes(id) {
//setTimeout("_attachSwipes("+id+")",500);
_attachSwipes(id);
}
function _attachSwipes(id) {
// Check if exists, if not try again later
if ($('#' + id).attr('id') == undefined) {
setTimeout("_attachSwipes("+id+")",500);
return;
}
/* Do your normal swipe attachment here */
}