Manipulate json data with jQuery - javascript

I am looking to load json data as html as show in this fiddle and below.
(function () {
var flickerAPI = "http://api.flickr.com/services/feeds/photos_public.gne?jsoncallback=?";
$.getJSON(flickerAPI, {
tags: "mount rainier",
tagmode: "any",
format: "json"
})
.done(function (data) {
$.each(data.items, function (i, item) {
$("<img>").attr("src", item.media.m).appendTo("#images");
if (i === 3) {
return false;
}
});
});
})();
jQuery("#images img").on("click", function (event) {
console.log('aaa');
});
I can get the json to load however I can't then get events such as on click to work with data that has been loaded with json, what am I doing wrong here?

You need to delegate your click events. They're being bound to items in the DOM, and then you're adding new items, and the events are not bound to them.
Try replacing your click binder with this:
jQuery(document).on("click", "#images img", function (event) {
console.log('aaa');
});
You'll want to replace document with the lowest-level consistent wrapper to avoid redundant traversal on click.

try this instead:
$("#images").on("click", "img", function (event) {
console.log('aaa');
});
the element with the id images exists when your event binding is attached, but the image elements do not. So using the on method, you can pass the img elements as a second parameter so that all img elements that are added after the page load are properly bound to this event handler.

Related

Transmit the Classname to a function

I have different "Profiles" in a Json-File. In an index.html different profile cards are shown and filled with the information of the Json-File. When you click on a Profil (Profil-Card) a detailed profile.html will be loaded and the function initateProfile will be executed.
$(document).on("click", ".profile-card", function () {
$('#page-content').load("sections/profile.html", function () {
initiateProfile($(this).data("profileid"));
});
});
I want to transmit the content of the profileid-class, which is the index for the Json-File.
function initiateProfile(id) {
var profile_data;
$.getJSON('data/profiles.json', function (data) {
profile_data = data[id];
$('.trn-name').text(profile_data.name);
$('.trn-studies').text(profile_data.studies);
$('.trn-stage').text(profile_data.stage);
});
}
Unfortunatly the id-variable is undefined. So the function can't get the information of the Json-File. What's the problem?
Thx
The issue is because this within the load() callback handler function is not the element which raised the event. It runs under a different scope. To fix this you need to save the element reference to a variable in the scope of the click handler, and use that within the callback, something like this:
$(document).on("click", ".profile-card", function () {
var profileId = $(this).data('profileid');
$('#page-content').load("sections/profile.html", function () {
initiateProfile(profileId);
});
});
Assuming that the data-profileid attribute is defined on the element which has the class .profile-card:
Your problem is this.
$(document).on("click", ".profile-card", function () {
$('#page-content').load("sections/profile.html", function () {
initiateProfile($(this).data("profileid")); // "this" points to the element with id "page-content"
});
});
One solution would be to use event.currentTarget:
$(document).on("click", ".profile-card", function (event) {
$('#page-content').load("sections/profile.html", function () {
initiateProfile($(event.currentTarget).data("profileid"));
});
});

Proper way to add dynamic HTML through .ajax() request

I have this example of the success part of a JSON Facebook Graph API request,
success: function(res){
console.log(res);
$(res.data).each(function(index, value){
var pic = 'https://graph.facebook.com/' + value.id + '/picture?width=200&height=200';
$('<img class="hover" src="'+pic+'" width="200" height="200">').load(function(){
$(this).appendTo("#results").fadeIn("fast");
$(this).wrap('');
})
});
},
That looks for the recieved data objects, puts the page-id picture inside an img tag, and when it's already loaded, it appends it to the #results div.
However I don't have control in img .hover elements. I tried with
$("img.hover").hover(function(){
$(this).fadeOut() //for example
});
and nothing happens. I suspect that's because any img did exist when the document was created. So, how could get those new elements?
You need to use event delegation, the .hover() method is a shortcut for registering mouseenter and mouseleave events so
$(document).on('mouseenter', 'img.hover', function () {
$(this).fadeIn() //for example
}).on('mouseleave', 'img.hover', function () {
$(this).fadeOut() //for example
});

Grabing ajax content after its load

sorry my bad english. I have a function to manipulate ajax like this:
$(document).on("click", ".ajax", function(e){
//dynamic contents here, getting the href value from links.
});
Now I need manipulate the content of the ajax request AFTER IS LOADED, adding some others functions to specific elements (add ajaxForm() to form elements, and others ). The case is: how to bind these functions WITHOUT a specific event? Per example, in the "contact.php" page and I want grab the tag to manipulate this, but the
$("form")
tag is not accessible.
If through a click, I would use
$(document).on("click", "element", function(e){
but no click event
How I can get this? Thks
Aditional information:
I want this:
ajaxLoader(content, "#mainDiv"); //loading a content. ajaxLoader is a .ajax() function
form1 = $("#mainDiv").find('#formOne'); //I need grad form like this
var options = {
beforeSend: function()
{
$("#progress").show(); //inacessible
$("#bar").width('0%'); //inacessible
$("#message").html(""); //inacessible
$("#percent").html("0%"); //inacessible
},
uploadProgress: function(event, position, total, percentComplete)
{
//foo
},
success: function()
{
//bar
},
complete: function(response)
{
//foo
}
};
$(form1).ajaxForm(options); //inacessible
Use the .success callback on your AJAX call. That's is why it is there.

Jquery simple ajax - Insert html

When a div is opnened i want to load html content into it via ajax. This is the code im working with:
http://jsfiddle.net/uhEgG/2/
$(document).ready(function () {
$('#country').click(function () {
$("#country_slide").slideToggle();
});
$('#close').click(function (e) {
e.preventDefault();
$('#country_slide').slideToggle();
});
});
The code I think I need is this:
$.ajaxSetup ({
cache: false
});
var ajax_load = "Loading...";
var loadUrl = "www.test.com/site.html";
$("#load_basic").click(function(){
$("#country_slide").html(ajax_load).load(loadUrl);
})
How can I make it work to make it load up when the div is opened by the code above, firstly because it is setup for a click function not a toggle function, and second, because the toggle doesn't seem to be able to distinguish if the div is open or not.
to make it load up when the div is opened by the code above
$("#country_slide").slideToggle(function(){
if($(this).is(':visible')){
$("#country_slide").html(ajax_load).load(loadUrl);
}
});
Try to delegate the events.. Looks like the element is not yet available in the DOm when the event is bound
Replace
$('#country').click(function () {
with
$(staticContainer).on('click', '#country', function () {
staticContainer is the element which is already in your DOM when the event is bound and the ancestor of country
Either store the slide state in a variable or in a data attribute liek this:
<div id="country_slide" data-state="1">
And make something like this:
$('#country').click(function () {
$("#country_slide").slideToggle();
if ($("#country_slide").attr("data-state") == 0)
$("#country_slide").html(ajax_load).load(loadUrl);
});

Jquery doesnot bind events to ajax added dom

I have an ajax function that loads the content of 4 checkboxes as follows:
$.ajax({
url : some url..,
dataType : 'json',
success : function(data) {
buildCheckboxes(data);
},
error : function(data) {
do something...
}
});
build checkboxes methods does something like this:
function updateNotificationMethods(items) {
var html = [];
$.each(items, function(i, item) {
htmlBuilder = [];
htmlBuilder.push("<input type='checkbox' class='checkbox-class' name='somename' value='");
htmlBuilder.push(item.id);
htmlBuilder.push("'");
htmlBuilder.push("/> ");
htmlBuilder.push(item.name);
htmlBuilder.push("<br/><br/>")
html.push(htmlBuilder.join(''));
});
$("#div").html(html.join(''));
}
i have also an event binder that should be triggered when checkbox value changes:
$(".checkbox-class").change(function() {
alert("change");
});
it works if i have the checkboxes html in the source (i.e. static) as opposed to the set up i have here, where i dynamically load the data from server.
is there something i can do so that binding take place timely?
peace!
This is because the element is not present when you bind your handler.
Try this:
$( document ).on( 'change', '.checkbox-class', function() {
alert("change");
});
Or if you are using an older version of jQuery (less than 1.7) ...
$( '.checkbox-class' ).live( function() {
alert("change");
});
Checkboxes are not available while you are binding the events. jsfiddle
Assuming that element with id div is present while binding the event.
$("#div").on("change",".checkbox-class",function() {
alert("change");
});
This code:
$(".checkbox-class").change(function() {
alert("change");
});
do not establishes a continuous and on-going rule, instead, this code attaches an event manager (in this case to the change event) to each matching DOM object that exists at the moment it is executed.
If you want you can re-execute this code (or one similar and narrow) each time you add checkboxes to the DOM.

Categories

Resources