Correctly parsing a response from YouTube API - javascript

I'm building a sample application with YouTube API (v3), that would provide a list of videos based on a search term. The concept is to populate the page using the data from the response.
I have used the client library documented in v3 to access the API, and send my request, however I don't know how to properly navigate through the data provided in the response in order to display the desired elements. The code below shows my script, where I am trying to access and list the title of the videos in the response:
$(function () {
//FUNCTION TO COLLECT QUERY TERM FROM SEARCH FORM
var $searchField = $('#search-text');
$('#mainSearch'). on ('submit', function(e){
e.preventDefault();
if ($searchField.val() !== '') { //IF SEARCH FORM IS NOT EMPTY
var $searchQuery = $searchField.val()+ ' parody'; //PREPARE SEARCH QUERY
makeRequest($searchQuery); //PASS SEARCH QUERY TO REQUEST FUNCTION
}
else {
$searchField.focus(); //ADD ERROR CLASS HERE
$searchField.blur(function (e){
//REMOVE ERROR CLASS HERE
});
}
});
function makeRequest(query){
var request = gapi.client.youtube.search.list({
part: 'snippet',
q: query
});
$('.content').empty();
request.execute(parseResponse);
}
function parseResponse(data) {
$.each(data, function (i, items){
var $infoDiv = $('<div></div>');
$infoDiv.append('<p>'+ items.snippet.title +'</p>');
$('.content').append($infoDiv);
});
}
});
//LOAD API CLIENT
function initClient() {
gapi.client.load('youtube', 'v3');
gapi.client.setApiKey('AIzaSyARVmOp3tBIA3ZgW6z4DK_-1sMJwulPvps');
}
However my page does get not populated with any data, and I get this error in my console:
Uncaught TypeError: Cannot read property 'title' of undefined
And here is the markup for my page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<title>Parrdy Template</title>
<!--
<Bootstrap></Bootstrap>-->
<link href="stylesheets/bootstrap.min.css" rel="stylesheet"/>
<link href="stylesheets/style.min.css" rel="stylesheet"/>
<!--
<HTML5>Shim and Respond.js IE8 support of HTML5 elements and media queries </HTML5>--><!--
<WARNING>
<Respond class="js">doesn't work if you view the page via file:// </Respond>
</WARNING>--><!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script><![endif]-->
</head>
<body>
<div class="container">
<div class="header">
<img src="/images/Logo1_mod.png" width="200">
<form role="form" id= "mainSearch" class="navbar-form navbar-right pull-right">
<div class="form-group">
<input type="text" id="search-text" placeholder="Search" class="form-control">
</div>
<button type="submit" id="vid-search" class="btn btn-sm btn-warning">Search</button>
</form>
</div>
{{{body}}}
<div class="footer">
<ul class="nav nav-pills pull-left">
<li><a class="customcolor" href="#">About</a></li>
<li><a class="customcolor" href="#">Contact Us</a></li>
</ul>
</div>
</div><!--container ends-->
<!--
<jQuery>(necessary for Bootstrap's JavaScript plugins) </jQuery>-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script><!--
<Include>all compiled plugins (below), or include individual files as needed</Include>-->
<script src="js/bootstrap.min.js"></script>
<script src="js/core1.1.js"></script>
<script src="https://apis.google.com/js/client.js?onload=initClient" type="text/javascript">
</script>
</body>
</html>
Any help on how to access the elements correctly from a YouTube API response would be appreciated. Thanks.

The first thing you'll want to keep in mind is that the stuff you are after is nested in the response as data so you need to access 'response.data' and within that data is an array of items. You'll want to access the first array with items[0] now you can grab the id from here or go deeper with .snippet or .statistic
get(url)
.then(response => {
id: response.DATA.items[0].id
title: response.DATA.items[0].snippet.title
}
.catch(
error => {console.log(error)}

You should change your loop like this:
$.each(data.videos, function (i, items){
var $infoDiv = $('<div></div>');
$infoDiv.append('<p>'+ items.snippet.title +'</p>');
$('.content').append($infoDiv);
});

Related

trouble loading javascript on html page load from jquery .load()

Working on a personal project with a navigation bar. I am using jquery x.load() to load html pages into a specific div. The pages load correctly into the div. However, one of the is using a jquery flipswitch. I am trying to read the state of this flipswitch, to no prevail. I have a main javascript file that loads the individual pages, which is basically my x.load(). I have a working jquery script for reading the switch state, that works when placed directly into the developers console. I have attempted this code both inline in the individual page as well as my main javascript file. When I place it inside the individual page, it will at times cause a race condition to develop.
I am looking for any suggestions, advice, or direction on being able to read the status of the flipswitch from the individual pages.
The first section of code is my javascript file. The second section of code, is both my individual page, as well as my main html page that loads the individual html page, respectively.
jQuery(document).ready(function() {
var SideNav = $('.side-nav'),
NavTrigger = $('.nav-trigger'),
Content = $('.content'),
ApartmentAlarm = $('#Alarm'),
$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
NavTrigger.on('click', function(event) {
event.preventDefault();
alert("click works");
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
ApartmentAlarm.on('click', function() {
//event.preventDefault();
Content.load('alarm.html');
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
</form>
<script type="text/javascript">
$(document).ready(function() {
console.log('hello');
$('#LeftSwitch').on('flipswitchcreate', function(event, ui) {
alert('me')
});
//$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
})
</script>
</body>
</html>
<html>
<head>
<title>
</title>
<link rel="stylesheet" href="apt.css">
</head>
<body>
<header class="page-header">
<div class="apartment-name">Carlson Casa</div>
<div class="data-top">
<ul class="top-data">
<li>Time</li>
<li>Outside Temp</li>
<li>Inside Temp</li>
<li>Menu<span></span></li>
</ul>
</div>
</header>
<main class="main-content">
<nav class="side-nav">
<ul>
<li>Apartment</li>
<li class="nav-label">Living Room</li>
<li>Alarm control</li>
<li>Chandelier</li>
<li class="nav-label">Bedroom</li>
<li>Lights</li>
<li>Alarm Clock</li>
</ul>
</nav>
<div class="content">
Controls go here
</div>
</main>
<script src="jquery-2.1.4.js"></script>
<script src="main.js"></script>
</body>
</html>
As you are using jQuery Mobile Flipswitch of type checkbox, you can get the status by checking the property checked. Here is a jQuery Mobile Flipswitch playground:
var cases = {false: "Unchecked", true: "Checked"};
function getStatus() {
$("#statusLeft").html(cases[$("#LeftSwitch").prop("checked")]);
$("#statusRight").html(cases[$("#RightSwitch").prop("checked")]);
}
$(document).on("change", "#LeftSwitch", function(e) {
var status = $(this).prop("checked");
$("#statusLeft").html("Changed to "+cases[status]);
});
$(document).on("change", "#RightSwitch", function(e) {
var status = $(this).prop("checked");
$("#statusRight").html("Changed to "+cases[status]);
});
function toggleLeft() {
var status = $("#LeftSwitch").prop("checked");
$("#LeftSwitch").prop("checked", !status).flipswitch("refresh");
}
function toggleRight() {
var status = $("#RightSwitch").prop("checked");
$("#RightSwitch").prop("checked", !status).flipswitch("refresh");
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no">
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.css">
<script src="https://code.jquery.com/jquery-1.11.2.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<div data-role="page" id="pageone">
<div data-role="content">
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<span id="statusLeft">Unchecked</span>
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
<span id="statusRight">Unchecked</span>
</form>
<button class="ui-btn" onclick="getStatus();">Get Status</button>
<button class="ui-btn" onclick="toggleLeft();">Toggle Left</button>
<button class="ui-btn" onclick="toggleRight();">Toggle Right</button>
</div>
</div>
</body>
</html>
By using the change event instead of click you will be notified of the flipswitch toggling also if you are setting the status in code.
Additional notes:
About what you are defining "race condition" i believe you are referring to one of the common mistakes when using jQuery Mobile, i.e. document.ready vs. page events. Please read this post here, and also take some time to read the whole story in deep in this great post of Omar here: jQuery Mobile “Page” Events – What, Why, Where, When & How? (you will find here some other useful posts about this topic).
Moreover: you are trying to update the flipswtches manually by setting the ui-flipswitch-active class by yourself, but i believe you will run into the problem of keeping the status and the ui consistent. So, you may better use the standard JQM way to set the flipswitch status by using flipswitch.refresh. There is already an example in my code snippet.
The last note: until you strongly need it - and you know how to versioning jQuery Mobile - please use the same version of these libraries in all your files, so in your case i believe the pair jQuery 2.1 + JQM 1.4.5 shall be just fine.
jQuery(document).ready(function() {
var SideNav = $('.side-nav'),
NavTrigger = $('.nav-trigger'),
Content = $('.content'),
ApartmentAlarm = $('#Alarm');
$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')});
NavTrigger.on('click', function(event) {
event.preventDefault();
alert("click works");
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
ApartmentAlarm.on('click', function() {
//event.preventDefault();
Content.load('alarm.html');
$([SideNav, NavTrigger]).toggleClass('nav-visible');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<title></title>
<link rel="stylesheet" href="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.css">
<script src="https://code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="https://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
</head>
<body>
<form>
<label for="LeftSwitch">Left Light:</label>
<input type="checkbox" data-role="flipswitch" name="LeftSwitch" id="LeftSwitch">
<br>
<label for="RightSwitch">Right Light</label>
<input type="checkbox" data-role="flipswitch" name="RightSwitch" id="RightSwitch">
</form>
<script type="text/javascript">
$(document).ready(function() {
console.log('hello');
$('#LeftSwitch').on('flipswitchcreate', function(event, ui) {
alert('me')
});
//$('.ui-flipswitch').click(function(){console.log($(this).hasClass('ui-flipswitch-active') ? 'On' : 'Off')})
})
</script>
</body>
</html>

req.user data from Passport JS not passed to Angular Controller

I'm building an app with an Express/Node backend and Angular JS for the front end. Kinda new to using this stack and I'm having a hard time receiving the data in an Angular Service + Controller
Backend: Users can authenticate with Facebook using Passport JS that attaches a users object to every request. I opened up an endpoint that checks if req.user exists, like so:
app.get('/checklogin', function(req,res,next){
if(req.user){
console.log("we found a user!!!");
console.log("name:" + req.user.displayName);
console.log("user id" + req.user.id);
return res.status(201).json(req.user);
} else {
console.log("there is no user logged in");
}
});
If the req.user exists, so the user is authenticated, it sends a JSON response.
What I'm trying to do is in Angular is sending a http.get to this /checklogin endpoint and handle the response. I want to bind to the scope if the user is authenticated (req.user exists or not), and if so bind displayName and Id as well, and hide show nav links and pages.
But my setup in Angular hits the API endpoint but doesnt seem to receive any data????:
.service("Login", function($http){
this.isLoggedIn = function(){
return $http.get("/checklogin")
.then(function(response){
console.log(response)
return response;
}, function(response){
console.log("failed to check login");
});
};
})
.controller("mainController", function($scope, Login){
Login.isLoggedIn()
.then(function(doc){
console.log(doc);
console.log(doc.data);
}, function(response){
alert(response);
});
})
the console.log(doc) and console.log(doc.data) don't log anything...... What am I doing wrong here?????
More info: the mainController is loaded in the index.html file:
<html lang="en" ng-app="myApp" ng-controller="mainController">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!--load jQuery-->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<!--load Bootstrap JS-->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
<!--load Angular JS-->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.8/angular-route.js"></script>
<!--latest compiled and minified Bootstap CSS-->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!--link custom CSS file-->
<link rel="stylesheet" type="text/css" href="/css/style.css">
<script src="/js/app.js"></script>
</head>
<body>
<!-- NAVBAR ================== ---->
<nav class="navbar navbar-default navbar-fixed-top">
<div class="container-fluid">
<div class="nav-header">
<a class="navbar-brand" href="#/">Votely</a>
</div>
<div class="collapse navbar-collapse" id="myNavbar">
<ul class="nav navbar-nav navbar-right">
<li class="active">Home</li>
<li>Sign in with Facebook</li>
<li>Sign Out</li>
</ul>
</div>
</div>
</nav>
<!-- Dynamically render templates Angular JS -->
<div class="container" ng-view>
</div>
</body>
Any help much appreciated, thanks!
You should return a promise from service if you are using then inside controller i.e.
.service("Login", function($http){
this.isLoggedIn = function(){
return $http.get("/checklogin");
};
.isLoggedIn function in your service should looks like this:
this.isLoggedIn = function(){
return $http.get("/checklogin");
}
thanks, I got it working now. I was using the browser in Cloud 9 IDE and the server was sending a 503 response, not sure why. It works now in Chrome and Firefox etc. after I set the service to return a promise!

How do I dynamically populate jQuery Mobile pages using JSON data?

I'm trying to get data from some external JSON (http://ip-api.com/json). I then want to use the keys to dynamically populate a listview. I want each list item to be a link, and when you click the link, the jQuery Mobile page will contain the key's matching value. I have two jQuery Mobile pages, one home, and one other.
I'm trying to achieve this by changing the id of the the second "data-role=page" div to the current key data, and also appending key data to h2, and appending the value data to p. It's creating a correct list of the keys, but when I click on the first item, the h2 contains ALL of the keys, and the p contains ALL of the values. How can I amend this so that each key/value pair ends up as the h2 and p of whichever jQuery Mobile page is currently being created by clicking the corresponding key list item?
I've been trying to use the code from How to populate a jQuery Mobile ListView with JSON data? but I can't quite get it working as it isn't using external JSON.
<!DOCTYPE html>
<html>
<head>
<title>Geo-Location Data</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/css/themes/geoLocation.css" />
<link rel="stylesheet" href="assets/css/themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="assets/js/geoLocation.js"></script>
</head>
<body>
<div data-role="page" id="homePage">
<div data-role="header">
<h1>Geo-Location Data</h1>
</div>
<div data-role="main" class="ui-content">
<div data-role="collapsible" data-collapsed="true">
<h2>Click here for Geo-Location Data</h2>
<ul id="list" data-role="listview" data-filter="true" data-inset="true" data-icon="user" data-autodividers="true">
</ul>
</div>
</div>
</div>
<div data-role="page" id="dataPage">
<div data-role="header">
<h2 id="dataHeading"></h2>
</div>
<div data-role="content">
<p></p>
</div>
</div>
</body>
</html>
$(document).ready( function() {
$.getJSON("http://ip-api.com/json", function(data){
$.each(data, function(key, val){
$("ul#list").append('<li>' + ''+ key + '' + '</li>');
$("ul#list").listview("refresh");
$("div#dataPage").attr("id", key);
$("h2#dataHeading").append(key);
$("p").append(val);
});
});
})
You are using an $.each loop so it keeps appending $("h2#dataHeading").append(key); & $("p").append(val); to the 2nd page as it loops through the json data so its not actually creating separate pages. All it does is change the id of the dataPage page once and it wont be able to find $("div#dataPage") thereafter so i'm surprised all the links in the items work except for the first one.
A more efficient way is use the data-* attribute to store the key and val directly on the list items, grab them upon click, append to the 2nd page and open the 2nd page dynamically. This alleviates the need for separate pages while keeping the DOM small
e.g
$(document).ready( function() {
$.getJSON("http://ip-api.com/json", function(data){
$.each(data, function(key, val){
$("ul#list").append('<li data-key="'+key+'" data-val="'+val+'"><a>'+ key + '</a></li>');
$("ul#list").listview("refresh");
});
});
//The list item click function
$("#list> li").on("click", function() {
var key= $(this).attr("data-key");
var val= $(this).attr("data-val");
$("#dataHeading").empty().append(key);
$("p").empty().append(val);
$(":mobile-pagecontainer").pagecontainer("change", "#dataPage", { transition: "slide" });
});
});
I suggest replacing $(document).ready with something like pagecreate as JQM works best with inbuilt page Events
When using $(":mobile-pagecontainer") you could also send data to a page but you will need another function like pagebeforeshow to append the data to the page before it displays it -- If you decide to do it this way, read the Notes for what versions is supported. JQM deprecates some events in versions in favor of new replacement events
A solution. What worked was entirely dispensing with the second JQM page, and creating it by appending the data to the body in the JavaScript. Here's the updated code.
<!DOCTYPE html>
<html>
<head>
<title>Geo-Location Data</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="assets/css/themes/geoLocation.css" />
<link rel="stylesheet" href="assets/css/themes/jquery.mobile.icons.min.css" />
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.4.5/jquery.mobile.structure-1.4.5.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="http://code.jquery.com/mobile/1.4.5/jquery.mobile-1.4.5.min.js"></script>
<script src="assets/js/geoLocation.js"></script>
</head>
<body>
<div data-role="page" id="homePage">
<div data-role="header">
<h1>Geo-Location Data</h1>
</div>
<div data-role="main" class="ui-content">
<div data-role="collapsible" data-collapsed="true">
<h2>Click here for Geo-Location Data</h2>
<ul id="list" data-role="listview" data-filter="true" data-inset="true" data-icon="arrow-r" data-autodividers="true">
</ul>
</div>
</div>
</div>
</body>
</html>
$(document).ready( function() {
$.getJSON("http://ip-api.com/json", function(data){
$.each(data, function(key, val){
$("ul#list").append('<li>' + ''+ key + '' + '</li>');
$("body").append('<div data-role="page" id="'+ key +'"><div data-role="header" id=""><h2 id="dataHeading"></h2 ></div><div data-role="content"><p>'+ val +'</p></div></div>');
$("ul#list").listview("refresh");
});
});
});

Content no load (jquery mobile)

I am developing an application with jQuery mobile and json bring data.
I have a problem loading content when I click on a button but if I enter directly to link the content is there.
Please, look:
if you click on any image it shows a page without content: http://www.example.com.ar/catalogoar/
But if you enter http://www.example.com.ar/catalogoar/arma_ampliada.html?id_arma=1 the content is there.
I can't find the problem. I already try with
$("#tabla_arma").table('refresh');
Please, learn how jQuery Mobile works before you post any more related questions. I am not trying to attack you but people here don't like this kind of questions.
To be able to solve this problem you need to understand how jQuery Mobile page handling works, and you can't solve this problem.
When jQuery Mobile handles pages only first HTML files is fully loaded into the DOM, all intermediate files are loaded only partially. When I say partially I mean HEAD will be stripped away and only FIRST data-role="page" will be loaded.
So if you have 2 pages, for example lets say first one is called index.html and second one is called arma_ampliada.html. When second page is initialized only content inside data-role="page" <div> will load into the DOM, everything else is going to get discarded, including HEAD javascript you need to load your data.
Read more about it here, you will also found solutions.
Your arma_ampliada.html page should look like this:
<html>
<head>
<title>Catálogo de Armas</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1" />
<!-- CSS -->
<link rel="stylesheet" href="css/jquery.mobile-1.4.2.css" />
<link rel="stylesheet" href="css/listview-grid.css">
<link rel="stylesheet" href="css/estilos.css">
<!-- JS -->
<script src="js/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).on("mobileinit", function()
{
$.mobile.defaultPageTransition = 'slide';
});
</script>
<script src="js/jquery.mobile-1.4.2.min.js"></script>
<!-- <script src="js/cordova.js"></script> -->
</head>
<body>
<div data-role="page" data-theme="a" id="demo-page" class="my-page">
<script>
var armas;
function obtenerArmaAmpliada(id_arma){
$.ajax({
type: 'GET',
data: {'id_arma' : id_arma},
dataType : 'jsonp',
url: 'service/datos.php?jsoncallback=?',
success:function(data){
armas = data.armas;
mostrarArmas();
},
error: function() {
alert("error");
}
});
}
function mostrarArmas ()
{
$("#arma_ampliada").html('');
$.each(armas, function(indice, receta)
{
$("#arma_ampliada").append('<tr><td><img src="'+receta.foto+'" class="ui-li-thumb" ><h2>'+receta.marca+'</h2><p>'+receta.modelo+'</p></td></tr>');
});
$("#tabla_arma").table('refresh');
}
$(function(){
var Url = location.href;
Url = Url.replace(/.*\?(.*?)/,"$1");
Variables = Url.split ("&");
for (i = 0; i < Variables.length; i++)
{
Separ = Variables[i].split("=");
eval ('var '+Separ[0]+'="'+Separ[1]+'"');
}
obtenerArmaAmpliada(id_arma);
});
</script>
<div data-role="header" style="overflow:hidden;">
<h1>Catálogo de Armas</h1>
Opciones
<div data-role="navbar">
<ul>
<li>Marcas</li>
<li>Calibre</li>
<li>Tipo</li>
</ul>
</div>
</div>
<div role="main" class="ui-content">
<div id="tabla_arma">
<table id="arma_ampliada">
</table>
</div>
</div><!-- /content -->
</div><!-- /page -->
</body>
</html>

Javascript: DOM elements updated via jquery.get() aren't responding to extant page listeners

I'm trying to update the content of a div (#slide-content) on clicking certain navigation elements (h2.pagenav). The content structure is uniform, and each requested HTML document contains two such nav elements ('Previous','Next'). However, my listener only fires once—for click events on the initial nav button present at page load, and I don't understand why.
My understanding is that when using jQuery's append() function instead of html(), the appended content should be registered with the DOM and thus available for event listening. Lil' help?
The page structure is pretty simple:
The HTML
<?php require('common.php'); ?>
<!doctype html>
<html class="no-js" lang="en">
<head>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<title>Ethogram Lab</title>
<link rel="stylesheet" href="css/foundation.css"/>
<link rel="stylesheet" href="css/foundation-icons.css"/>
<link rel="stylesheet" href="css/app.css"/>
<script src="js/vendor/modernizr.js"></script>
</head>
<body>
<div id="slide-content">
<div class="slide">
<div class="row">
<div class="row">
<!---- content ---->
</div>
<div class="row">
<div class="small-4 small-centered columns">
<h2 data-link="slide_0" class="medium button expand text-center pagenav">Start <i class="fi-play"></i></h2>
</div>
</div>
</div>
</div>
</div>
</div>
<script src='js/vendor/jquery.js'></script>
<script src='js/foundation.min.js'></script>
<script>
$(document).foundation();
</script>
<script src='js/app.js'></script>
</body>
</html>
The Javascript
And here is the relevant it of app.js
/**
* PAGE VARS
*/
var DS = '/';
var WEBROOT = "127.0.0.1"+DS+"ethogram"+DS;
var PHP = ".php";
/**
* DOM LISTENERS
*/
$(".pagenav").click(function() {
console.log("*** pagenav listener has fired");
var loc = $(this).attr('data-link');
var pageNum = loc.substr(-2) == "_" ? loc.substr(-1) : loc.substr(-2);
var URL = WEBROOT+"slides"+DS+loc+PHP;
$.get(URL, function(data) {
$("#slide-content").html('').append(data).fadeIn();
});
});
The ".on()" function should be used. ".live()" is deprecated.
.on() function
$("body").on("click", ".pagenav", function() {
// do something
});
You should use
$("body").on ("click",".pagenav",function(){
// Your code go here
})
This function will detect the items created programatically
See Documentation

Categories