i'm using this template for a personal project.
https://github.com/blueimp/Bootstrap-Image-Gallery
and there is this code here that gets photos from flickr. This code uses the method flickr.interestingness.getList which takes tags as an argument as seen here. http://www.flickr.com/services/api/flickr.interestingness.getList.html
I want to pass in tags as an argument, but I can't figure out the syntax for doing so in ajax or w/e the format being used in this code is.
// Load images via flickr for demonstration purposes:
$.ajax({
url: 'http://api.flickr.com/services/rest/',
data: {
format: 'json',
method: 'flickr.interestingness.getList',
api_key: 'API_KEY_abc123'
},
dataType: 'jsonp',
jsonp: 'jsoncallback'
}).done(function (data) {
var gallery = $('#gallery'),
url;
$.each(data.photos.photo, function (index, photo) {
url = 'http://farm' + photo.farm + '.static.flickr.com/' +
photo.server + '/' + photo.id + '_' + photo.secret;
$('<a data-gallery="gallery"/>')
.append($('<img>').prop('src', url + '_s.jpg'))
.prop('href', url + '_b.jpg')
.prop('title', photo.title)
.appendTo(gallery);
});
This seems like a better project:
http://petejank.github.io/js-flickr-gallery/
/*
* Bootstrap Image Gallery JS Demo 3.0.0
* https://github.com/blueimp/Bootstrap-Image-Gallery
*
* Copyright 2013, Sebastian Tschan
* https://blueimp.net
*
* Licensed under the MIT license:
* http://www.opensource.org/licenses/MIT
* Plugin was modified by ravindu
*/
(function( $ ) {
$.fn.flickr = function(options) {
var url = 'http://api.flickr.com/services/rest/?jsoncallback=?';
var settings = $.extend( {
'api_key': 'YOUR API',
}, options);
function view_image(event) {
var target = $(event.target);
if(target.is('img')) {
var url = target.attr('data-url');
var cache = new Image();
cache.src = url;
var gallery = target.parents('.flickr-gallery:first').children('div.viewport');
var info = gallery.children('div.image-info');
var image = gallery.children('img');
image.fadeOut('slow', function () {
image.attr('src', url);
image.fadeIn('slow');
info.html(target.attr('data-title') + '<br />' + target.attr('data-tags'));
});
}
}
return this.each(function() {
var gallery = $(this);
gallery.addClass('flickr-gallery');
gallery.append('<h2></h2><h3></h3><div class="viewport"></div><div class="browser"><ul></ul></div><div class="clear"></div>');
$.getJSON(url, {
method: 'flickr.photosets.getInfo',
api_key: settings.api_key,
photoset_id: settings.photoset_id,
format: 'json'
}).success(function(state) {
gallery.children('h3').html(state.photoset.description._content);
gallery.find('.loader').addClass('activate');
$.getJSON(url, {
method: 'flickr.photosets.getPhotos',
api_key: settings.api_key,
media: 'photos',
photoset_id: settings.photoset_id,
format: 'json',
extras: 'url_sq,url_m,url_b,date_taken,tags'
}).success(function(state) {
$('.loader').removeClass('activate');
var list = gallery.find('ul:first');
list.html('');
list.on('click', view_image);
$.each(state.photoset.photo, function(index, photo){
baseUrl = 'http://farm' + photo.farm + '.static.flickr.com/' +
photo.server + '/' + photo.id + '_' + photo.secret;
list.append('<a href="' + this.url_m + '" title="' + this.title + '" data-gallery="" > <img src="' + this.url_sq + '" title="' + this.title + '" ' +
'data-title="' + this.title + '" ' +
'data-url="' + this.url_m + '" ' +
( this.date_taken ? 'data-date="' + this.date_taken + '" ' : '' ) +
'data-tags="' + this.tags + '" ' +
'/></a>');
});
}).fail(function(state) {
alert("Unable to retrieve photo set");
});
}).fail(function(state) {
alert("Unable to retrieve photo set information");
});
});
};
})( jQuery );
$(document).on('ready', function(){
$('#photos-1').flickr({ photoset_id:'72157640241840746'});
$('#photos-2').flickr({ photoset_id:'72157640251299195'});
$('#photos-3').flickr({ photoset_id:'72157640241840746'});
$('#photos-4').flickr({ photoset_id:'72157640251299195'});
$('#photos-5').flickr({ photoset_id:'72157640241840746'});
});
Related
I have multiple classes with the same tag (.offer) I am going through a loop and it adds the image to all my .offer divs. I just want to add the image specific to the user who posted. How can I do this? Assume the backend is working completely fine
jQuery (1st function)
function getOffers(key) {
dict = {
'key': key// pk value of post sent to retrieve offers to it
};
generateCSRFToken();
$.ajax({
url: "/retrieve_offers/",
method: "POST",
data: JSON.stringify(dict),
success: function (data) {
data = JSON.parse(data);
console.log(appendUserImage(38));
$("#offercontainer").empty();
$(".offer").empty();
for (var i = 0; i < data.length; i++) {
var string = data[i].fields.author_name;
$("#offercontainer").append(
"<div class='offer'>" +
"<p class=offername>" + string + "</p>" +
"<p class=offertext> offered his " + " " + data[i].fields.item_name + "</p>" +
"</div>"
);
appendUserImage(data[i].fields.author);
}
},
error: function () {
}
})
}
jQuery (2nd function)
function appendUserImage(key) {
dict = {
'key': key// pk value of post sent to retrieve offers to it
};
generateCSRFToken();
$.ajax({
url: "/get_user/",
method: "POST",
data: JSON.stringify(dict),
success: function (data) {
$('<img />', {
src: data["image"],
class: "offer_user_image"
}).appendTo($('.offer'))
},
error: function () {
}
});
}
I just want to append the image to its respective offer div pls help
you can pass to appendUserImage the div getOffers function creates or do something like this, add an unique key selector to the created .offer container and targeting it in the appendUserImage function.
in function getOffers(key) {
$("#offercontainer").append(
"<div class='offer' data-author-key='" + data[i].fields.author +"'>" +
"<p class=offername>" + string + "</p>" +
"<p class=offertext> offered his " + " " + data[i].fields.item_name + "</p>" +
"</div>");
appendUserImage(data[i].fields.author);
in function appendUserImage(key) {
$('<img />', {
src: data["image"],
class: "offer_user_image"
}).appendTo($('.offer[data-author-key="' + key + '"]'))
thanks for the people who tried answering I managed to fix my problem by using nth child and doing this:
for (var i = 0; i < data.length; i++) {
var string = data[i].fields.author_name;
$("#offercontainer").append(
"<div class='offer'>" +
"<p class=offername>" + string + "</p>" +
"<p class=offertext> offered his " + " " + data[i].fields.item_name + "</p>" +
"</div>"
);
appendUserImage(i,data[i].fields.author);
}
2nd function:
function appendUserImage(i,key) {
dict = {
'key': key// pk value of post sent to retrieve offers to it
};
generateCSRFToken();
$.ajax({
url: "/get_user/",
method: "POST",
data: JSON.stringify(dict),
success: function (data) {
$('<img />', {
src: data["image"],
class: "offer_user_image"
}).appendTo($('.offer:nth-child(' + (i+1) + ')'))
},
error: function () {
}
});
}
I want to get all of the image from my Tumblr blog, (no limit)
even if I change the limit to the large number, by default it became 20 images, I just want to know what is wrong on my codes that I created, please help.. thanks in advance
please check the fiddle above to check the result.
here's my code on jsFiddle
$(document).ready(function(){
var tumblrUrl = 'http://api.tumblr.com/v2/blog/';
var blogUrl = 'blog.campbrandgoods.com';
var apiType = '/posts';
var apiKey = 'VtZPFbyp0dLYfOespTdo6oJyOE0nZx4anBSa46j9OoJO4SBIjg';
var limit = 995;
var postUrl = tumblrUrl + blogUrl + apiType + '?api_key=' + apiKey + '&limit=' + limit;
var tileContainer = $('ul#tiles');
$.ajax({
url: postUrl,
type: 'get',
dataType: 'jsonp',
complete: function(){
},
success: function( strData ){
console.log(strData.response.posts);
var posts = strData.response.posts;
$.each(posts, function (i, v) {
if(typeof v.photos !== 'undefined') {
var n = Math.floor(Math.random() * 6);
var info = $($.parseHTML(v.caption)).text();
tileContainer.append('<li class="item"><div class="tile-img-container"><img src="' + v.photos[0].alt_sizes[2].url + '"></div><div class="tile-info-container"><a class="various fancybox" href="' + v.post_url + '">' + info + '</a></div></li>');
//tileContainer.append('<li class="item"><div class="tile-img-container"><img src="' + v.photos[0].alt_sizes[2].url + '"></div><div class="tile-info-container"><a title="' + info + '" class="various fancybox" href="' + v.photos[0].original_size.url + '">' + info + '</a></div></li>');
}
});
tileContainer.gridalicious({selector: '.item', gutter: 5, animate: true});
$('ul#tiles').on('click', 'li.item', function (e) {
var href = $(this).find('.tile-info-container').find('a').attr('href');
$(this).parents('.item').find('.tile-info-container').find('a').trigger('click');
window.open(href);
//$(this).find('.tile-info-container').find('a').trigger('click');
});
$('ul#tiles').on('click', 'li.item a', function (e) {
e.preventDefault();
});
/*
$("a.fancybox").fancybox({
'type': 'image',
'transitionIn' : 'elastic',
'transitionOut' : 'elastic',
'speedIn' : 600,
'speedOut' : 200,
'overlayShow' : true,
'autoScale' : false,
'autoSize' : false,
overlayOpacity: 0.7,
overlayColor: '#000',
onStart :function () {
$('#fancybox-inner').css('width', '97%');
$('#fancybox-inner').css('height', '97%');
},
onComplete: function(){
$('#fancybox-inner').css('width', '97%');
$('#fancybox-inner').css('height', '97%');
}
});
*/
$('.tile-img-container').on('click', function (e) {
$(this).parents('.item').find('.tile-info-container').find('a').trigger('click');
e.preventDefault();
});
}
});
});
#tiles li.item .tile-info-container {
background-color: rgba(0,0,0,0.7);
cursor: pointer;
display: none;
position: absolute;
top: 0;
width: 100%;
height: 100%;
font-size: 11px;
}
<div class="container-fluid">
<div id="page" class="row">
<div class="col-md-12 details">
<ul id="tiles">
</ul>
</div>
</div>
</div>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet">
On the Tumblr api docs, it is clearly stated that for the request /posts, you're only allowed to have a limit that goes from 1 to 20.
The approach I'd take would be a recursive function that takes an offset argument. (from the following I've removed some code that wasn't working / was commented out)
function GetImages(offset) {
var postUrl = tumblrUrl + blogUrl + apiType + '?api_key=' + apiKey + '&limit=20&offset=' + offset;
$.ajax({
url: postUrl,
type: 'get',
dataType: 'jsonp',
complete: function(){
},
success: function( strData ){
console.log(strData.response.posts);
var posts = strData.response.posts;
$.each(posts, function (i, v) {
if(typeof v.photos !== 'undefined') {
var n = Math.floor(Math.random() * 6);
var info = $($.parseHTML(v.caption)).text();
tileContainer.append('<li class="item"><div class="tile-img-container"><img src="' + v.photos[0].alt_sizes[2].url + '"></div><div class="tile-info-container"><a class="various fancybox" href="' + v.post_url + '">' + info + '</a></div></li>');
//tileContainer.append('<li class="item"><div class="tile-img-container"><img src="' + v.photos[0].alt_sizes[2].url + '"></div><div class="tile-info-container"><a title="' + info + '" class="various fancybox" href="' + v.photos[0].original_size.url + '">' + info + '</a></div></li>');
}
});
$('ul#tiles').on('click', 'li.item', function (e) {
var href = $(this).find('.tile-info-container').find('a').attr('href');
$(this).parents('.item').find('.tile-info-container').find('a').trigger('click');
window.open(href);
//$(this).find('.tile-info-container').find('a').trigger('click');
});
$('ul#tiles').on('click', 'li.item a', function (e) {
e.preventDefault();
});
$('.tile-img-container').on('click', function (e) {
$(this).parents('.item').find('.tile-info-container').find('a').trigger('click');
e.preventDefault();
});
// actual changed part
if (typeof offset === "undefined") {
offset = 0;
}
// (to avoid having to load a hundred pages for each time it was tested, there was also this in the if: `offset < 100 &&`)
if (((offset + 20) < strData.response.total_posts)) {
GetImages(offset + 20);
}
}
});
}
GetImages(0);
When I try push some element to array and display random element, browser return that array is not define. Where is problem?
var dir = "./images/radovi/";
var ext = ".png";
var slike = [];
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + ext + ")").each(function () {
var ime_slike = this.href.replace(window.location.host, "").replace("http:///", "");
slike.push(dir + ime_slike + ext);
});
}
});
$('<img src="' + slike[Math.floor(Math.random() * slike.length)] + '">').appendTo('#radovi');
AJAX is Asynchronous. The code that populates your array is being called after the code that uses the array. Move the code that creates the image into the success handler:
var dir = "./images/radovi/";
var ext = ".png";
var slike = [];
$.ajax({
url: dir,
success: function (data) {
$(data).find("a:contains(" + ext + ")").each(function () {
var ime_slike = this.href.replace(window.location.host, "").replace("http:///", "");
slike.push(dir + ime_slike + ext);
});
if (slike.length) {
$('<img src="' + slike[Math.floor(Math.random() * slike.length)] + '">').appendTo('#radovi');
}
}
});
I want to clone a html control and then append to another control.
I have written code
ko.bindingHandlers.multiFileUpload = {
init: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor()),
controlId = ko.utils.unwrapObservable(options.controlId);
//primaryKey = ko.utils.unwrapObservable(options.primaryKey);
var progressMonitorID = controlId + '-ProgressMonitor';
var progressIndicatorID = controlId + '-ProgressIndicator';
$(element).after('<div id=' + progressMonitorID + ' class="progress progress-striped active">'
+ '<div id=' + progressIndicatorID + ' class="bar" style="width: 0%;"></div>'
//+ '<input type="hidden" id="imageKey_"' + controlId + ' name="imageKey" value=' + primaryKey + '></div>'
+ '</div>');
$('#' + progressMonitorID).hide();
$('#' + progressIndicatorID).hide();
},
update: function (element, valueAccessor, allBindingsAccessor, viewModel, bindingContext) {
var options = ko.utils.unwrapObservable(valueAccessor()),
imageKey = ko.utils.unwrapObservable(options.imageKey),
imageForeighKey01 = ko.utils.unwrapObservable(options.imageForeighKey01),
uploadUrl = ko.utils.unwrapObservable(options.uploadUrl),
controlId = ko.utils.unwrapObservable(options.controlId),
refreshUri = ko.utils.unwrapObservable(options.refresh),
formName = ko.utils.unwrapObservable(options.formName);
var progressMonitorID = controlId + '-ProgressMonitor';
var progressIndicatorID = controlId + '-ProgressIndicator';
var formID = controlId + '-form';
var fileInputID = controlId + '-fileInput';
if (uploadUrl) {
$(element).change(function () {
if (element.files.length) {
var $this = $(this),
fileName = $this.val();
// var formData = new FormData($('#' + formName)[0]);
var $form = $('<form enctype="multipart/form-data" id=' + formID + '></form>');
// $form.append('<input id=' + fileInputID + 'name=' + fileInputID + ' type="file" />');
$form.append('<input type="hidden" id="imageKey_"' + controlId + ' name="imageKey" value=' + imageKey + '>');
$form.append('<input type="hidden" id="imageForeignKey_"' + controlId + ' name="imageForeighKey01" value=' + imageForeighKey01 + '>');
$("#" + controlId).clone().appendTo($form);
$form.hide();
$('body').append($form);
var formData = new FormData($($form)[0]);
$.ajax({
url: uploadUrl,
type: 'POST',
// Form data
data: formData,
//Options to tell JQuery not to process data or worry about content-type
cache: false,
contentType: false, //'multipart/form-data',
processData: false,
xhr: function () {
var xhr = new window.XMLHttpRequest();
//Upload progress
xhr.upload.addEventListener("progress", function (evt) {
if (evt.lengthComputable) {
var percentComplete = evt.loaded / evt.total * 100 + "%";
//Do something with upload progress
$('#' + progressMonitorID).show();
$('#' + progressIndicatorID).width(percentComplete);
//alert(percentComplete);
}
}, false);
return xhr;
}
})
.done(function (data, textStatus, jqXHR) {
if (refreshUri) {
//alert("success");
//var path = '../MapView/DownloadMap?ref=' + Math.random();
var path = refreshUri + 'ref=' + Math.random();
options.refresh(path);
}
})
.fail(function (jqxhr, status, errorMsg) { alert("Status : " + status + " Error :" + errorMsg); })
.always(function () {
// alert("complete");
$('#' + progressMonitorID).hide();
$('#' + progressIndicatorID).hide();
$('#' + formID).remove();
});
}
});
}
}
}
and html binding is
<input type="file" tabindex="9"
data-bind="attr: {
id: 'RoadMap' + $index(), name: 'RoadMap' + $index()
},
multiFileUpload: {
controlId: 'RoadMap' + $index(),
formName: 'frmPage3a',
imageKey: StageDetailID,
imageForeighKey01: CourseInfoRoadID,
uploadUrl: '/api/Image/UploadMapFile'
}
" />
this code works very fine into FireFox browser but not work in IE and Chrome.here the problem is .clone() method of jquery.
Is it possible? Thanks.
You are assigning id with an underscore and this is why not working. Use two backslashes to escape meta character. Like $("#your\\_id")
see more info here
I want to show the weather on my website. I have some javascript code like
$(function () {
// Specify the ZIP/location code and units (f or c)
//var loc = '10001'; // or e.g. SPXX0050
//var u = 'f';
var loc = 'TUXX0002';
//var loc = 'TUXX0014';
var u = 'c';
//var locA = 'TUXX0002';
//var locI = 'TUXX0015';
var query = "SELECT item.condition FROM weather.forecast WHERE location='" + loc + "' AND u='" + u + "'";
var cacheBuster = Math.floor((new Date().getTime()) / 1200 / 1000);
var url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json&_nocache=' + cacheBuster;
window['wxCallback'] = function (data) {
var info = data.query.results.channel.item.condition;
$('#wxIcon').css({
backgroundPosition: '-' + (61 * info.code) + 'px 0'
}).attr({
title: info.text
});
$('#wxIcon2').append('<img src="http://l.yimg.com/a/i/us/we/52/' + info.code + '.gif" width="34" height="34" title="' + info.text + '" />');
$('#wxTemp').html(info.temp + '°' + (u.toUpperCase()));
};
$.ajax({
url: url,
dataType: 'jsonp',
cache: true,
jsonpCallback: 'wxCallback'
});
});
For now it shows only one location. (with loc variable). I want to add a dropdown or something like a change location link. Than if user selects 'A' location it shows 'A location's weather' etc. I added a dropdown item. Here is the code.
<select id="wxCombo">
<option value="istanbul">istanbul</option>
<option value="ankara">ankara</option>
<option value="izmir">izmir</option>
</select>
Than I add some javascript code for change function, on the same javascript page.
var wxCombo = $("#wxCombo").val();
$("#wxCombo").change(function()
{
if (wxCombo == 'Ankara')
{
loc 'TUXX0002';
}
});
It didn't worked. I need some guide for fixing this issue.
Here's a few things I would change.
First off, declare a function that will update the weather information, based on location:
function updateWeather(loc, u)
{
var query = "SELECT item.condition \
FROM weather.forecast \
WHERE location='" + loc + "' AND u='" + u + "'",
url = 'http://query.yahooapis.com/v1/public/yql?q=' + encodeURIComponent(query) + '&format=json';
$.ajax({
url: url,
dataType: 'jsonp', // this automatically disables cache too
success: function(data) {
var info = data.query.results.channel.item.condition;
$('#wxIcon').css({
backgroundPosition: '-' + (61 * info.code) + 'px 0'
}).attr({
title: info.text
});
$('#wxIcon2').append('<img src="http://l.yimg.com/a/i/us/we/52/' + info.code + '.gif" width="34" height="34" title="' + info.text + '" />');
$('#wxTemp').html(info.temp + '°' + (u.toUpperCase()));
}
});
}
Then, hook this into the .change() handler:
$("#wxCombo").change(function() {
var country = $(this).val();
if (country == 'ankara') {
updateWeather('TUXX0002', 'C');
}
// etc.
});
Demo: http://jsfiddle.net/ZF3aW/
on first glance you are missing an = sign...
var wxCombo = $("#wxCombo").val();
$("#wxCombo").change(function()
{
if (wxCombo == 'Ankara')
{
loc **=** 'TUXX0002';
}
});