Reputation: 5132
I have the following code and am using jquery mobile. When I click on an element, it is not going to the "page2". Any advice on how to fix this?
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My first jQuery Mobile code</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css">
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.custom_listview_img {
margin:0px;
padding:0px;
background-repeat:no-repeat;
background-size:100%;
height:150px;
}
ul {list-style : none; padding:0px;}
</style>
<script>
$(function() {
$(".changePageButton").click(function() {
$.mobile.changePage("#page2");
});
});
</script>
<script type="text/javascript">
$(document).ready(function(){
var url='http://api.yipit.com/v1/deals/?key=mRSTBQsB49CdMXTW&division=san-francisco&tag=restaurants&lat=37.871087&lon=-122.270913&callback=?';
$.getJSON(url,function(json){
$.each(json.response.deals,function(i,item){
$("#results").append('<ul data-role="listview" data-inset="true" data-theme="d" data-divider-theme="a" style="white-space:normal"><a class = "changePageButton" data-transition="slide"><li data-role="list-divider" role="heading" class="ui-li ui-li-divider ui-btn ui-bar-c ui-corner-top">'+item.business.name+'</li><li class="custom_listview_img" style = "background-image:url('+item.images.image_smart+');"></li></a></ul>');
});
});
});
</script>
</head>
<body>
<div data-role="page" data-theme="c">
<div data-role="header" data-theme="b">
<h1>Dealoka</h1>
</div>
<div data-role="content" id = "results">
<!-- Display results of parsing json here -->
</div>
</div>
<div data-role="page" id="page2" data-add-back-btn="true">
<div data-role="header">
<h1>Page 2</h1>
</div>
<div data-role="content">
<p>Welcome to Page 2</p>
</div>
</div>
</body>
</html>
<!-- Sort with jquery: http://stackoverflow.com/questions/5560493/html5-data-attribute-sort -->
Upvotes: 0
Views: 76
Reputation: 10993
Your problem is that at the time your binding your event to the changePageButton
it is not yet part of the DOM, you need to either use event delegation or bind it after it's been attached to the DOM.
When you use event delegation, what you do is bind the event to a higher existing element (up to the document
if necessary) in the DOM
and check for the selector when the event bubbles up. Note that it's better to bind it to the closest higher element.
For example you can use the jQuery .on method to bind the event using event delegation
$(document).on('click','.changePageButton', function() {
$.mobile.changePage("#page2");
});
Upvotes: 1
Reputation: 3254
Use event delegation because you are creating the event dynamically;
$(function() {
$("body").on('click', '.changePage', function() {
$.mobile.changePage("#page2");
});
});
Upvotes: 0