Facebook images on website, editing jquery - php

This is "my code" for pulling images from Facebook and displaying them.
But I want to wrap images around < a href="image.source" class="highslide" onclick="return hs.expand(this) >
Please help me outputting:
<a href="image.source" class="highslide" onclick="return hs.expand(this)>
<img src"image.source" width="167" height="167">
</a>
Original code:
<script type="text/javascript" src="underscore-min.js"></script>
<script type="text/javascript">
$.getJSON('http://graph.facebook.com/261512740659107/photos').then(function (response) {
// 0-8, 0 returns the largest available images, 8 the smallest
var imageIndex = 4;
var images = _(response.data)
.chain()
.pluck('images')
.pluck(imageIndex)
.value();
console.log(images);
_(images).each(function (image) {
$('#image-container').append(
$('<img>').attr('src', image.source).attr('height', 167).attr('width', 167));
});
});
</script>

You can use the jQuery wrap() function to put the <a> tag around your <img> tags.
Just use appendTo() instead to get the instance of the new element so that you can then wrap() it.
$.getJSON('http://graph.facebook.com/261512740659107/photos').then(function (response) {
// 0-8, 0 returns the largest available images, 8 the smallest
var imageIndex = 4;
var images = _(response.data)
.chain()
.pluck('images')
.pluck(imageIndex)
.value();
_(images).each(function (image) {
$($('<img>').attr({'src': image.source, 'height': 167, 'width': 167})).appendTo('#image-container').wrap('<a href="' + image.source + '" class="highslide" onclick="return hs.expand(this);" />');
});
});

Related

on size change remove the existing image and add other image dynamically without reloading the page

I am building a website. In that I am using bootstrap carousel in which I am adding images dynamically according to the orientation of the screen.
By JavaScript I am measuring the width and height of the screen and posting the width, height, and id to the php via ajax.
in php the width, height, id is received, php is fetching all the data from the mysql table with respect to the id.
if width is greater then height then it is landscape orientation and it converts all the values under landscape column into json.
Otherwise it is portrait orientation and it converts all the values under portrait column into json.
The ajax calls back the json data and appends it to the data correctly.
My problem is while the screen is in landscape mode it shows all the landscape images (example 5 images). When the orientation is changed to portrait the ajax works and fetches the portrait images (example 5 images) and adds to the existing landscape images resulting in 10 images. If i change the orientation again, landscape images are added again resulting in 15 images. After refreshing the page only 5 images are shown with respect to the orientation.
How to get this without refreshing the page (when the orientation is changed from landscape to portrait, all landscape images should be removed and portrait images should be added without refreshing the page).
<html>
<head>
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body onresize="send_screen_size()" onload="send_screen_size()">
<div class="container">
<div id="myCarousel" class="carousel slide" data-ride="carousel" >
<div class="carousel-inner"></div>
</div>
</div>
</body>
</html>
function send_screen_size(sParam){
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
for (var i = 0; i < sURLVariables.length; i++)
{
var sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] == sParam)
{
return decodeURIComponent(sParameterName[1]);
}
}
if(window.innerWidth !== undefined && window.innerHeight !== undefined) {
var w = window.innerWidth;
var h = window.innerHeight;
} else {
var w = document.documentElement.clientWidth;
var h = document.documentElement.clientHeight;
}
var
width = + w ;
height = + h;
var width = width = + w ;
var height = height = + h;
var pro_id = send_screen_size('pro_id');
$.ajax({
async : "false", // !!!MAKE SURE THIS ONE IS SET!!!
type:"POST",
url: "carousel.php",
data:{width: width, height: height, pro_id:pro_id},
dataType: 'json',
success: function (data){
$.each(data, function(i, item) {
$('.carousel-inner').append('<div class = item>'+item.orientation+'</div>')
})
$('.carousel-inner > :first-child').addClass("active");
},
error: function(xhr, status, error) {
var err = eval("(" + xhr.responseText + ")");
console.log(error);
}
});
}
You could try
$('.carousel-inner .item').remove();
before $.ajax call.
You might want to throttle or debounce your window onresize event listener also.

Replace broken images with jQuery or JavaScript

I have a web page that includes 10's of thousands of images. Sometimes the image isn't available so a broken image is displayed in the clients browser.
The broken image is in the following URL format: www.domain.com/t.php?src=p/dd5e5b08_1.jpg.
How do I use jQuery to get the set of images, filter it to broken images then replace the src?
The following does not work:
above the closing </head> tag
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js">
</script>
above the closing tag
<script type="text/javascript">
$(window).load(function() {
$("img").each(function(){
var image = $(this);
if(image.context.naturalWidth == 0 || image.readyState == 'uninitialized'){
$(image).unbind("error").attr("src", "/images/no_image.png");
}
});
});
</script>
This code might help you:
function imgError(image){
image.onerror = "";
image.src = "/images/noimage.gif";
return true;
}
<img src="image.png" onerror="imgError(this);"/>
Try CodeFiddle Demo
This may help you:
$(document).ready(function () {
let images = ['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg'];
let image_html = '';
$.each(images, (key, value) => {
image_html += '<img src="img/' + value + '"/>';
});
$('#imgcontainer').html(image_html);
$('img').on('error', function () {
$(this).replaceWith('<img src="img/no-photo.jpg"/>');
});
});

Duplicate photos in instagram pagination

I'm trying to pull photos from specific tag. Found an awesome tutorial and I've managed to pull photos from Instagram with pagination.
The problem I'm facing now is duplicate photos being displayed if it reaches to the end of the photos.
HTML Source
<!DOCTYPE html>
<html>
<head>
<script src='http://code.jquery.com/jquery-1.7.2.min.js' type='text/javascript' charset='utf-8'></script>
<script src='javascripts/application.js' type='text/javascript' charset='utf-8'></script>
<link rel='stylesheet' href='stylesheets/application.css' type='text/css' media='screen'>
<title>Photo Stream </title>
<meta name="description" content="Search for instagram images online.">
<meta name="author" content="Omar Sahyoun">
</head>
<body>
<!--<form id='search'>
<button class="button" type="submit" id="search-button" dir="ltr" tabindex="2">
<span class="button-content">Search</span>
</button>
<div class='search-wrap'>
<input class='search-tag' type='text' tabindex='1' value='cats' />
</div>
</form>-->
<h2 id="search">Photo Stream </h2>
<div id='photos-wrap'>
</div>
<div class='paginate'>
<a class='button' style='display:none;' data-max-tag-id='' href='#'>View More...</a>
</div>
</body>
</html>
Javascript File
// Add trim function support for IE7/IE8
if(typeof String.prototype.trim !== 'function') {
String.prototype.trim = function() {
return this.replace(/^\s+|\s+$/g, '');
}
}
// Instantiate an empty object.
var Instagram = {};
// Small object for holding important configuration data.
Instagram.Config = {
clientID: 'xxxx',
apiHost: 'https://api.instagram.com'
};
// Quick and dirty templating solution.
Instagram.Template = {};
Instagram.Template.Views = {
"photo": "<div class='photo'>" +
"<a href='{url}' target='_blank'><img class='main' src='{photo}' width='250' height='250' style='display:none;' onload='Instagram.App.showPhoto(this);' /></a>" +
"<span class='heart'><strong>{count}</strong></span><span class='comment'><strong>{count2}</strong></span>" +
"<span class='avatar'><iframe src='//www.facebook.com/plugins/like.php?href={url}&send=false&layout=button_count&width=40&show_faces=true&action=like&colorscheme=light&font&height=21&' scrolling='no' frameborder='0' style='border:none; overflow:hidden; width:80px; height:21px;' allowTransparency='true'></iframe></span>" +
"</div>"
};
Instagram.Template.generate = function(template, data){
var re, resource;
template = Instagram.Template.Views[template];
for(var attribute in data){
re = new RegExp("{" + attribute + "}","g");
template = template.replace(re, data[attribute]);
}
return template;
};
// ************************
// ** Main Application Code
// ************************
(function(){
function init(){
bindEventHandlers();
}
function toTemplate(photo){
photo = {
count: photo.likes.count,
count2: photo.comments.count,
avatar: photo.user.profile_picture,
photo: photo.images.low_resolution.url,
url: photo.link
};
return Instagram.Template.generate('photo', photo);
}
function toScreen(photos){
var photos_html = '';
$('.paginate a').attr('data-max-tag-id', photos.pagination.next_max_id)
.fadeIn();
$.each(photos.data, function(index, photo){
photos_html += toTemplate(photo);
});
$('div#photos-wrap').append(photos_html);
}
function generateResource(tag){
var config = Instagram.Config, url;
if(typeof tag === 'undefined'){
throw new Error("Resource requires a tag. Try searching for cats!");
} else {
// Make sure tag is a string, trim any trailing/leading whitespace and take only the first
// word, if there are multiple.
tag = String(tag).trim().split(" ")[0];
}
url = config.apiHost + "/v1/tags/" + tag + "/media/recent?callback=?&count=10&client_id=" + config.clientID;
return function(max_id){
var next_page;
if(typeof max_id === 'string' && max_id.trim() !== '') {
next_page = url + "&max_id=" + max_id;
}
return next_page || url;
};
}
function paginate(max_id){
$.getJSON(generateUrl(tag), toScreen);
}
function search(tag){
resource = generateResource(tag);
$('.paginate a').hide();
$('#photos-wrap *').remove();
fetchPhotos();
}
function fetchPhotos(max_id){
$.getJSON(resource(max_id), toScreen);
}
function bindEventHandlers(){
$('body').on('click', '.paginate a.button', function(){
var tagID = $(this).attr('data-max-tag-id');
fetchPhotos(tagID);
return false;
});
// Bind an event handler to the `click` event on the form's button
$('form#search button').click(function(){
// Extract the value of the search input text field.
var tag = $('input.search-tag').val();
// Invoke `search`, passing `tag`.
search(tag);
// Stop event propagation.
return false;
});
}
function showPhoto(p){
$(p).fadeIn();
}
Instagram.App = {
search: search,
showPhoto: showPhoto,
init: init
};
})();
$(function(){
Instagram.App.init();
// Start with a search on cats; we all love cats.
Instagram.App.search('hwplus');
});
Please help me to find a way to disable the 'View More' button if photos have reached the end.
And is there a way to add cache in JSON object and fetch variables from Javascript?
Thanks and appreciate.
Once you reach the end of the photos, the next_max_tag_id won't exist. You'll need to check if next_max_tag_id exists and if not, disable the button. You'll implement your new code on this line, maybe make a variable for photos.pagination.next_max_id and when the user clicks the button, check if the variable is defined.
Untested code:
var next_max = photos.pagination.next_max_id;
if (next_max == 'undefined') {
var next_max = 'end';
$('.paginate a').addClass('disabled');
}
//define .disabled in your CSS
$('.paginate a').attr('data-max-tag-id', next_max).fadeIn();

How to show loading image at load() proccess with js

I want to show loading image in my page..
I have a load() function and i need to display a loading image in the center of my page while its loading and i am using load() with backbone router.
I think i need javascript to do it but i dont know how to show it only at load() proccess.
**You can use in this way**
function showLoadingMsg() {
$('#loading-message').css({
display : 'block'
});
}
function hideLoadingMsg() {
$('#loading-message').remove();
}
**the place where you want to show loading gif**
<!--loding image goes here-->
<div style="display:none" id="loading-message"><img src="<?php echo base_url(); ?>assests/img/loading.gif" /></div>
**When to show and hide should be in**
obj.fbId ="14232";
showLoadingMsg();
$.post("<?= base_url() ?>welcome/insertVideos",obj,
function(success){
hideLoadingMsg();
}, "json");
I am also php developer i did this using jquery..
You can use it through Jquery like this:-
Just confirm your jquery script are present..
<div id="popup1" class="popup_block">
<?php echo $this->Html->image('loader2.gif'); ?>
<h4>Processing Please Wait...! </h4>
</div>
And you have to call this function
function open_loader(){
if(enrollFlag==0){
return false;
}
//Fade in Background
jQuery('body').append('<div id="fade"></div>'); //Add the fade layer to bottom of the body tag.
jQuery('#fade').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer
var popID = 'popup1';
//var popWidth = 500;
//Fade in the Popup and add close button
jQuery('#' + popID).css({ 'width': '250' });
//Define margin for center alignment (vertical + horizontal) - we add 80 to the height/width to accomodate for the padding + border width defined in the css
var popMargTop = (jQuery('#' + popID).height() + 80) / 2;
var popMargLeft = (jQuery('#' + popID).width() + 80) / 2;
//Apply Margin to Popup
jQuery('#' + popID).css({
'margin-top' : -popMargTop,
'margin-left' : -popMargLeft,
'display' : 'block'
});
}
This function will show loader image when it will execute..
Or if you stick to load()
do like this:-
<input type="button" onclick="example_request()" value="Click Me!" />
<div id="example-placeholder">
<p>Placeholding text</p>
</div>
function example_ajax_request() {
$('#example-placeholder').html('<p><img src="/images/loader.gif" width="220" height="19" /></p>');
$('#example-placeholder').load("/examples/loaded.html");
}
Lets say you have a div with image tag in it.. If you have ajax request than You can show or hide the div like this... (place this code on .ready function)
$('#loadingDiv')
.hide() // hide it initially
.ajaxStart(function() {
$(this).show();
})
.ajaxStop(function() {
$(this).hide();
});
And if you do not have ajax call than use like this....
function Load()
{
$('#loadingDiv').hide(); // hide it initially
$('#loadingDiv').show() ;
//-------------Your code here of form loading------
//-------------Your code here of form loading------
//-------
//-------
$('#loadingDiv').hide();// hide it in the last
}

jCarousel initializing/refreshing/reloading each time clicked on image

I am making a picture preview with jCarousel (http://sorgalla.com/projects/jcarousel/), but faced with one problem: I do not know how could I reload/refresh jCarousel dynamic list.
I have few categories of images. When I click on a picture in one of that, I need that the list would be created and preview start with that element. I have some code, but do not know how to make it re-create all list after clicking on other image that preview start with other image.
Here are my code:
$(document).ready(function(){
$("ul#stage li").live('click', function() {
var ul = $(this).parent();
var index = +(ul.children().index(this))+1;
var mycarousel_itemList = [ ];
$('li[data-id]').each(function () {
var $this = $(this);
mycarousel_itemList.push({
url : $this.attr("data-img"),
title : $this.attr("data-title")
});
});
function mycarousel_itemLoadCallback(carousel, state) {
for (var i = carousel.first; i <= carousel.last; i++) {
if (carousel.has(i)) {
continue;
}
if (i > mycarousel_itemList.length) {
break;
}
carousel.add(i, mycarousel_getItemHTML(mycarousel_itemList[i-1]));
}
};
function mycarousel_getItemHTML(item) {
return '<img src="' + item.url + '" width="800" height="600" alt="' + item.url + '" />';
};
alert(index);
jQuery('#mycarousel').jcarousel({
itemLoadCallback: {onBeforeAnimation: mycarousel_itemLoadCallback},
size: mycarousel_itemList.length,
scroll: 1,
start: index,
wrap: 'last',
animation: 'fast',
visible: 1
});
document.getElementById('popup-content').style.background='url('+$(this).attr("data-img")+') no-repeat center';
document.getElementById('fades').style.display='block';
document.getElementById("light").style.display = "block";
$("#light").fadeTo("slow", 1);
});
});
Everything is like that: there are images > I click on one of those > popup shows with jCarousel and one visible image and then I could scroll through all other images.
It is working good, but just a first time. When I click on other image (after closing popup), the view starts with that image which was opened last.
If something are not clear enough - please, ask. I will try to make it more precisely.
Thanks for your help!
You can recreate jCarousel, first use $('#mycarousel').remove(); and next init jCarousel again. I didn't really understand what you're trying to do, but this can help in most cases, of course jCarousel should have Destroy method but it hasn't.
And why you don't use jquery selectors in some cases?

Categories