I have a problem that I need to sort out in javascript I believe, but dont know how to begin with it, so hopefully someone from the javascript community may be able to help please.
Basically, the following code allows me to load 10 images into a slideshow carousel.
However, these images are either 600px x 400px Portrait or 400px x 600 Landscape. The problem I have is that the Landscape images
are vertically aligned to the top of the container.
I have managed to get around this by creating two classes in my CSS file image-P & image-L
image-L has a "padding-top:100px " which successfully vertially aligns the landscape images in the centre.
What I'd like to do is for the code to check which images are landscape and then create
return '<img src="Images/' + item.url + '" class="image-L" alt="" />';
and anything else use
return '<img src="Images/' + item.url + '" class="image-P" alt="" />';
many thanks in advance.
Cheers Rob.
<script type="text/javascript">
var mycarousel_itemList = [
{ url: "Image1.jpg" },
{ url: "Image2.jpg" },
{ url: "Image3.jpg" },
{ url: "Image4.jpg" },
{ url: "Image5.jpg" },
{ url: "Image6.jpg" },
{ url: "Image7.jpg" },
{ url: "Image8.jpg" },
{ url: "Image9.jpg" },
{ url: "Image10.jpg" }
];
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]));
}
};
/**
* Item html creation helper.
*/
function mycarousel_getItemHTML(item) {
return '<img src="Images/' + item.url + '" class="image-L" alt="" />';
};
jQuery(document).ready(function () {
jQuery('#mycarousel').jcarousel({
size: mycarousel_itemList.length,
itemLoadCallback: { onBeforeAnimation: mycarousel_itemLoadCallback }
});
});
You could try loading the image into JavaScript [1] with the Image class [2] and check the height/width of the image itself to determine which class to apply, but this would slow things down if you did it at load time. (I don't know if the browser would cache the file or not for when you went to display it later).
It seems like it'd be better to wait and apply the style after the image has been added to the document/displayed.
You could probably use jQuery to get the height of the (browser) view and the height of the image then absolutely position the image to be centered. (That'd be more flexible if you wanted to use different image sizes later).
http://www.techrepublic.com/article/preloading-and-the-javascript-image-object/5214317
http://www.w3schools.com/jsref/dom_obj_image.asp
My solution:
<script type="text/javascript">
function preloader() {
// counter
var i = 0;
// create object
imageObj = new Image();
// set image list
images = new Array();
images[0] = "Images/image1.jpg"
images[1] = "Images/image2.jpg"
images[2] = "Images/image3.jpg"
images[3] = "Images/image4.jpg"
images[4] = "Images/image5.jpg"
images[5] = "Images/image6.jpg"
images[6] = "Images/image7.jpg"
images[7] = "Images/image8.jpg"
images[8] = "Images/image9.jpg"
images[9] = "Images/image10.jpg"
// start preloading
for (i = 0; i <= 9; i++) {
imageObj.src = images[i];
}
}
</script>
<script type="text/javascript">
var mycarousel_itemList = [
{ url: "Images/Image1.jpg" },
{ url: "Images/Image2.jpg" },
{ url: "Images/Image3.jpg" },
{ url: "Images/Image4.jpg" },
{ url: "Images/Image5.jpg" },
{ url: "Images/Image6.jpg" },
{ url: "Images/Image7.jpg" },
{ url: "Images/Image8.jpg" },
{ url: "Images/Image9.jpg" },
{ url: "Images/Image10.jpg" }
];
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]));
}
};
/**
* Item html creation helper.
*/
function mycarousel_getItemHTML(item) {
return '<img src="' + item.url + '" class="image" alt="" />';
};
jQuery(document).ready(function () {
jQuery('#mycarousel').jcarousel({
size: mycarousel_itemList.length,
itemLoadCallback: { onBeforeAnimation: mycarousel_itemLoadCallback }
});
});
</script>
<%# Page Title="" Language="C#" MasterPageFile="~/rwmSite.master" AutoEventWireup="true"
CodeFile="Portfolio.aspx.cs" Inherits="Portfolio" %>
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="Server">
<link href="../Styles/Site.css" rel="stylesheet" type="text/css" />
<script src="../Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery.jcarousel.min.js" type="text/javascript"></script>
<script type="text/javascript">
var mycarousel_itemList = [
{ url: "Image1.jpg" },
{ url: "Image2.jpg" },
{ url: "Image3.jpg" },
{ url: "Image4.jpg" },
{ url: "Image5.jpg" },
{ url: "Image6.jpg" },
{ url: "Image7.jpg" },
{ url: "Image8.jpg" },
{ url: "Image9.jpg" },
{ url: "Image10.jpg"}];
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]));
}
};
/**
* Item html creation helper.
*/
function mycarousel_getItemHTML(item) {
var x = new Image(); x.src = item.url;
while (!x.complete)
if (x.height <= 400)
return '<img src="../Images/' + item.url + '" class="image-L" alt="" />';
else
return '<img src="../Images/' + item.url + '" class="image-P" alt="" />';
};
jQuery(document).ready(function () {
jQuery('#mycarousel').jcarousel({
size: mycarousel_itemList.length,
itemLoadCallback: { onBeforeAnimation: mycarousel_itemLoadCallback }
});
});
</script>
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="Server">
<div id="wrap" align="center">
<div class=" jcarousel-skin-tango">
<div class="jcarousel-container jcarousel-container-horizontal">
<div class="jcarousel-clip jcarousel-clip-horizontal">
<ul id="mycarousel" class="jcarousel-list jcarousel-list-horizontal">
</ul>
</div>
<div class="jcarousel-prev jcarousel-prev-horizontal">
</div>
<div class="jcarousel-next jcarousel-next-horizontal">
</div>
</div>
</div>
</div>
</asp:Content>
Related
I'm trying to lazy-load an image & video file with jQuery, following the example from the URL below:
https://varvy.com/pagespeed/defer-videos.html
https://varvy.com/pagespeed/defer-images.html
The problem is that my paginated data loaded onScroll by jQuery, but all of my image and video wasn't loaded. How can I solve this?
[ Pagination ]
$(window).on('scroll', function () {
if ($(window).scrollTop() + $(window).height() == $(document).height()) {
page += 1;
if (page <= maxPages) {
$.ajax({
beforeSend: function () {
$('.loader').html('Loading....');
},
type: 'GET',
url: 'blog/postloader?page=' + page,
data: { 'page': page },
cache: false,
success: function (data) {
$('.loader').html('Load More...');
$('.blogItems').append(data);
}
});
}
else { $('.loader').html('No More Post Available'); }
}
[ Lazy Loader function ]
function delayImg() {
var imgDefer = document.getElementsByTagName('img');
for (var i = 0; i < imgDefer.length; i++) {
if (imgDefer[i].getAttribute('data-src')) {
imgDefer[i].setAttribute('src', imgDefer[i].getAttribute('data-src'));
}
}
}
//window.onload = delayImg;
// Lazy Load Video
function delayVid() {
var vidDefer = document.getElementsByTagName('iframe');
for (var i = 0; i < vidDefer.length; i++) {
if (vidDefer[i].getAttribute('data-src')) {
vidDefer[i].setAttribute('src', vidDefer[i].getAttribute('data-src'));
}
}
}
//window.onload = delayVid;
function start() {
delayImg();
delayVid();
}
window.onload = start;
you can combine the function with jQuery
function delayMedia() {
$('img, iframe').each(function() {
if (!$(this).attr('src')) { // set only if src is empty
var dataSrc = $(this).data('src');
if (dataSrc)
this.src = dataSrc;
}
});
}
call it on page load and after Ajax
$('.blogItems').append(data);
delayMedia();
And your function are not "really" lazy load, usually it appear after element position reached not on page load
function isVisible(el) {
var rect = el.getBoundingClientRect(),
elemTop = rect.top,
elemBottom = rect.bottom;
return (elemTop >= 0) && (elemBottom <= window.innerHeight);
}
function delayMedia() {
$('img, iframe').each(function() {
if (!$(this).attr('src')) { // set only if src is empty
var dataSrc = $(this).data('src');
if (dataSrc && isVisible(this)){
console.log(dataSrc)
this.src = dataSrc;
}
}
});
}
$(window).on('scroll', function() {
delayMedia();
});
.dh {
height: 300px;
display: block
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<p class="dh">scroll</p>
<img src="" data-src="https://www.planwallpaper.com/static/images/1712173free-wallpaper.jpg" />
<p class="dh">scroll</p>
<img src="" data-src="https://www.planwallpaper.com/static/images/3d_falling_leaves.jpg" />
<p class="dh">scroll</p>
<img src="" data-src="https://www.planwallpaper.com/static/images/free-wallpapers-640x400.jpg" />
So I have a MVC code that generates something like this
<div class="photoset">
<img />
<img />
</div>
<div class="photoset">
<img />
<img />
<img />
</div>
And I'm trying to make a jQuery to infinite scroll and as the user is scrolling, it generates more photosets.
I was somewhat successful in doing that but, after I generate more photosets with my infinite scroll, the newly added code won't work with my previous jQuery plugin to navigate between images.
Here is the jQuery code to navigate:
jQuery
$(document).ready(function () {
$('.photoset').each(function () {
$(this).data('counter', 0);
$items = $(this).find('img')
$(this).data('numItems', $items.length);
$(this).closest('.row').prev('.row').find('.nav-informer').text($(this).data('counter') + 1 + " de " + $(this).data('numItems'));
if (($items.eq(0).width() / $items.eq(0).height()) < 1) {
$(this).css({
width: "445",
height: "667",
margin: "auto"
});
}
});
var showCurrent = function (photoset) {
$items = photoset.find('img');
var counter = photoset.data('counter');
var numItems = $items.length;
var itemToShow = Math.abs(counter % numItems);
$items.fadeOut(1000);
$items.eq(itemToShow).fadeIn(1000);
};
/* ---------------------------------------------- /*
* Prev
/* ---------------------------------------------- */
$('.prev').on('click', function () {
var photoset = $(this).closest('.row').prev('.row').find('.photoset');
photoset.data('counter', photoset.data('counter') - 1);
if (photoset.data('counter') < 0)
photoset.data('counter', photoset.data('numItems') - 1);
photoset.closest('.row').prev('.row').find('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));
showCurrent(photoset);
});
/* ---------------------------------------------- /*
* Next
/* ---------------------------------------------- */
$('.next').on('click', function () {
var photoset = $(this).closest('.row').prev('.row').find('.photoset');
photoset.data('counter', photoset.data('counter') + 1);
if (photoset.data('counter') > photoset.data('numItems') - 1)
photoset.data('counter', 0);
photoset.closest('.row').prev('.row').find('.nav-informer').text(photoset.data('counter') + 1 + " de " + photoset.data('numItems'));
showCurrent(photoset);
});
});
And the Ajax function to call for more photosets, passing the page number:
Ajax
var page = 0,
inCallback = false,
hasReachedEndOfInfiniteScroll = false;
var ulScrollHandler = function () {
if (hasReachedEndOfInfiniteScroll == false &&
($(window).scrollTop() == $(document).height() - $(window).height())) {
loadMoreToInfiniteScrollUl(moreRowsUrl);
resizeNewElements();
}
}
function loadMoreToInfiniteScrollUl(loadMoreRowsUrl) {
if (page > -1 && !inCallback) {
inCallback = true;
page++;
$(".loading").show();
$.ajax({
type: 'GET',
url: loadMoreRowsUrl,
data: "pageNum=" + page,
success: function (data, textstatus) {
if (data != '') {
$(".infinite-scroll").append(data);
}
else {
page = -1;
}
inCallback = false;
$(".loading").hide();
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
}
}
function showNoMoreRecords() {
hasReachedEndOfInfiniteScroll = true;
}
And this is the function that calls the infinite scroll:
$(function () {
$(".loading").hide();
});
var moreRowsUrl = '#Url.Action("index", "home")';
$(window).scroll(ulScrollHandler);
I did some research but couldn't stabilish a reason why my code doesn't work, tried some things but did not have success. If anyone could help me, would be great! Thanks in advance, and sorry for any mistake, I'm extremely new with jQuery and Ajax.
You can try with the event delegation for the click event on .prev and .next elements:
$(document).ready(function(){
$(document).on('click', '.prev', function(){.....});
$(document).on('click', '.next', function(){.....});
});
I have a set of images and videos. And I want to implement a player which can loop through all the images and videos.
As an example,
A - image, B - video, C - image;
assets = [A, B, C];
I want a html player which loop through this array, first show A(image) for an interval[5s], then autoplay the B(video) and end of the video, shows C(image) for an interval(5s) and repeat the flow. I have tried something like below code. But this is not a solution for a video.
var previewContainer = $(".previews-container");
var curIndex = 1;
appendMediaElement(loopAssets[0]); //initial
setInterval(function() {
if(curIndex >= loopAssets.length) {
curIndex = 1;
}
appendMediaElement(loopAssets[curIndex]); //loopAssets array contains all the images and vidoes with meta data which is retrive from a ajax call
curIndex++;
}, 5000);
function appendMediaElement(asset) {
var mediaEl = "";
if(asset.mediaType == "IMAGE") {
mediaEl = '<img id="lp-preview-image" src="' + asset.contentUrl + '">';
previewContainer.html(mediaEl);
} else if(asset.mediaType == "VIDEO") {
mediaEl = "<video id='lp-preview-video' autoplay controls>";
mediaEl += "<source src='"+ asset.contentUrl + "' type='" + asset.contentType + "'>";
mediaEl += "</video>";
previewContainer.html(mediaEl);
}
}
<div class="col-xs-8">
<div id="loop-preview">
<div class="item previews-container" style="width: 700px; height: 450px">
<!-- images/vidoes-->
</div>
</div>
</div>
any better solution will be appreciated!
Here is a solution with what you mentioned on your comments:
Images will be displayed for 5 seconds, and
Videos will be displayed completely
before moving to the next media element.
Trying to change your code minimally, this is a list of things that could be done:
Remove the setInterval (but keep the function that changes the media, rename it to something like changeMedia)
At the end of the code when it is an image, add a setTimeout that calls the new function that you created (changeMedia) after 5 seconds.
At the end of the code when it is a video, add a listener to the end of the video (ended event) in which you call the function that you created (changeMedia).
And that should be it. For my code, I assumed this is the data that you get from AJAX (it follows all the requirements from your original code, although it's possibly just a minified version of what you get):
var loopAssets = [
{ contentUrl: "http://lorempixel.com/200/200/abstract/", contentType: "image/jpg", mediaType:"IMAGE" },
{ contentUrl: "http://www.w3schools.com/html/mov_bbb.mp4", contentType: "video/mp4", mediaType: "VIDEO"},
{ contentUrl: "http://lorempixel.com/200/200/people/", contentType: "image/jpg", mediaType:"IMAGE" }
];
So, here is a working demo (see the comments in the places that I changed):
var loopAssets = [
{ contentUrl: "http://lorempixel.com/200/200/abstract/", contentType: "image/jpg", mediaType:"IMAGE" },
{ contentUrl: "http://www.w3schools.com/html/mov_bbb.mp4", contentType: "video/mp4", mediaType: "VIDEO"},
{ contentUrl: "http://lorempixel.com/200/200/people/", contentType: "image/jpg", mediaType:"IMAGE" }
];
var previewContainer = $(".previews-container");
var curIndex = 1;
appendMediaElement(loopAssets[0]);
// removed the setInterval but kept the function
function changeMedia() {
if(curIndex >= loopAssets.length) {
// modified this so it would display the first image/video when looping
curIndex = 0;
}
appendMediaElement(loopAssets[curIndex]);
curIndex++;
};
function appendMediaElement(asset) {
var mediaEl = "";
if(asset.mediaType == "IMAGE") {
mediaEl = '<img id="lp-preview-image" src="' + asset.contentUrl + '">';
previewContainer.html(mediaEl);
// image: go to the next media after 5 seconds
setTimeout("changeMedia()", 5000);
} else if(asset.mediaType == "VIDEO") {
mediaEl = "<video id='lp-preview-video' autoplay controls>";
mediaEl += "<source src='"+ asset.contentUrl + "' type='" + asset.contentType + "'>";
mediaEl += "</video>";
previewContainer.html(mediaEl);
// video: go to the next media when the video ends
document.getElementById("lp-preview-video").addEventListener("ended", function(e) {
changeMedia();
});
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="col-xs-8">
<div id="loop-preview">
<div class="item previews-container" style="width: 700px; height: 450px">
</div>
</div>
</div>
As I said, this is the simplest change to make your code work as you defined in your question and comments, to make it better/more efficient, you may want to look into doing other enhancements (for example: hide/show instead of create/delete elements).
Here is the JSFiddle demo
//CODE
<!DOCTYPE html>
<html>
<head>
<style>
body{
width: 100vw;
height: 100vh;
margin: 0 !important;
display: -webkit-flex;
display: flex;
-webkit-justify-content: center;
justify-content: center;
}
#media{
display: -webkit-flex;
display: flex;
-webkit-align-self: center;
align-self:center;
}
#media>img{
height: 500px;
width: 500px;
}
</style>
<script>
var imgFormat = ["jpg","png"];
var content = [
"http://cdn.wonderfulengineering.com/wp-content/uploads/2014/04/space-wallpapers-9.jpg",
"http://ak8.picdn.net/shutterstock/videos/1694950/preview/stock-footage-operator-cleans-lens-of-professional-videocamera-and-on-background-scenery-are-prepared.mp4",
"http://www.sciencesortof.com/wp-content/uploads/2015/04/218_space_beer.jpg",
"http://www.spirit1059.com/pics/Feeds/Articles/2015611/118317/Beach.jpg",
"http://ak7.picdn.net/shutterstock/videos/3775625/preview/stock-footage-northern-lights-aurora-borealis-reflected-on-a-lake-timelapse-in-iceland.mp4"
];
document.onreadystatechange = function(){
if(document.readyState == "interactive"){mediaChange();}
}
function mediaChange(){
var mediaBox = document.getElementById("media");
setInterval(function(){
var media = mediaBox.children[0];
var key = content.indexOf(media.getAttribute("src"));
if((key+1) == content.length){key = 0;}
else{key += 1;}
var format = content[key].substr(content[key].length - 3);
changeMedia(mediaBox,media,key,format);
}, 5000);
}
function changeMedia(mediaBox,media,key,format){
if(imgFormat.indexOf(format) < 0){
var ele = document.createElement("video");
ele.setAttribute("autoplay", true);
}
else{var ele = document.createElement("img");}
ele.setAttribute("src",content[key]);
mediaBox.replaceChild(ele,media);
}
</script>
</head>
<body>
<section id="media">
<img src="http://cdn.wonderfulengineering.com/wp-content/uploads/2014/04/space-wallpapers-9.jpg">
</section>
</body>
</html>
I have downloaded and implemented some jquery code that makes a photo gallery on my website from an instagram hashtag. I have been trying to edit this code so that clicking on the images in the gallery show up in a lightbox rather than following a link back to instagram.
Here is the the source for the code: http://www.jqueryscript.net/social-media/jQuery-Plugin-To-Create-An-Endless-Instagram-Gallery-embedstagram.html
The Lightbox code I have been using is fancybox: http://www.jqueryscript.net/lightbox/Responsive-jQuery-Lightbox-With-Amazing-CSS3-Effects-Fancy-Box-2.html
On my site the necessary components are loaded for both Jqueries and the function is run like so:
<script>
$(document).ready(function(){
$(".ins_popup").fancybox({
openEffect : 'fade',
closeEffect : 'fade'
});
});
</script>
I have found the href in the original gallery jquery that links to instagram and edited it to include the class 'ins_popup' like so:
function renderPhotos(data) {
$.each(data.data, function (i, photo) {
photo = '<li class="photo"><img src="' + photo.images.standard_resolution.url.replace(/\\/, "") + '"></li>';
This does not seem to work however and the link now just opens an enlarged version of the picture rather than opening it in fancybox. I have tested each of the components (fancybox / hashtag gallery) separetly without problem, I just can't seem to get them to talk to one another.
And the associated code:
<!DOCTYPE html>
<html>
<head>
<title>Embedstagram jQuery Plugin Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<!-- Include CSS Fies -->
<link href="https://www.googledrive.com/host/0B_9gRWttmryISVpkTGFhVV8yajQ" rel="stylesheet" type="text/css" >
<link href="http://www.jqueryscript.net/css/jquerysctipttop.css" rel="stylesheet" type="text/css">
<link href="http://cdnjs.cloudflare.com/ajax/libs/normalize/3.0.1/normalize.css" rel="stylesheet" type="text/css">
<link href="http://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.css" rel="stylesheet" type="text/css">
<!-- Include jQuery -->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<!-- Include fancybox library -->
<script src="http://cdnjs.cloudflare.com/ajax/libs/fancybox/2.1.5/jquery.fancybox.min.js"></script>
<script>
$(document).ready(function(){
$(".ins_popup").fancybox({
openEffect : 'fade',
closeEffect : 'fade'
});
});
</script>
</head>
<body>
<div class="jquery-script-clear"></div>
<h1 style="margin:150px auto 30px auto;">Embedstagram jQuery Plugin Demo</h1>
<div id="embedstagram"></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="https://www.googledrive.com/host/0B_9gRWttmryIbE0yNUJaeHNOQVk"></script>
<script type="text/javascript">
$(document).ready(function () {
$('#embedstagram').embedstagram({
client_id: '6f3244d01df94bb98785d04861561307',
hashtag: '#neverlutionsoundsystem' ,
thumb: 'tile'
});
});
</script>
</body>
</html>
and the Jquery for the gallery which I have edited:
/*global jQuery, window*/
(function ($) {
$.fn.embedstagram = function (options) {
var $this = this,
next_url = '';
var settings = $.extend({
client_id: '',
username: '',
hashtag: '#neverlutionsoundsystem',
count: 20,
responsive: true,
load_more: true,
thumb: 'default',
theme: 'default'
}, options);
settings.hashtag = settings.hashtag.replace('#', '');
$this
.addClass('embedstagram')
.addClass('thumb-' + settings.thumb)
.addClass('theme-' + settings.theme)
.append('<ul></ul>')
.append('Loading..');
var $photos = $this.find('ul'),
$button = $this.find('#function-button');
function resize() {
if (settings.responsive) {
var e = $this.width();
var $photo = $('.photo');
if (1024 >= e && e > 768) {
$photo.css({'width': '25%', 'padding-bottom': '25%'});
} else if (768 >= e && e > 570) {
$photo.css({'width': '33.3%', 'padding-bottom': '33.3%'});
} else if (570 >= e && e > 400) {
$photo.css({'width': '50%', 'padding-bottom': '50%'});
} else if (400 > e) {
$photo.css({'width': '100%', 'padding-bottom': '100%'});
} else {
$photo.css({'width': '20%', 'padding-bottom': '20%'});
}
}
}
function renderPhotos(data) {
$.each(data.data, function (i, photo) {
photo = '<li class="photo"><img src="' + photo.images.standard_resolution.url.replace(/\\/, "") + '"></li>';
$photos.append(photo);
return i <= (settings.count);
});
}
function getUrl(user_id) {
var modifier;
if (user_id) {
modifier = 'users/' + user_id;
} else if (settings.hashtag) {
modifier = 'tags/' + settings.hashtag;
}
if (next_url) {
return next_url;
}
return 'https://api.instagram.com/v1/' + modifier + '/media/recent/?&client_id=' + settings.client_id + '&count=' + settings.count;
}
function getPhotos(user_id) {
$button.text('Loading..');
$.ajax({
type: "GET",
dataType: 'jsonp',
url: getUrl(user_id),
success: function (data) {
if (data.meta.error_message) {
var error_message = 'Error: ' + data.meta.error_message.toLowerCase();
$button.text(error_message).addClass('error');
return false;
}
if (!settings.load_more) {
$this.addClass('hide-load-more');
}
$button.text('Load More');
renderPhotos(data);
next_url = data.pagination.next_url;
if (!next_url) {
$button.text('No more images').addClass('disabled');
}
resize();
},
error: function () {
$button.text('Error: unknown').addClass('error');
}
});
}
if (settings.username) {
$.ajax({
type: "GET",
dataType: 'jsonp',
url: 'https://api.instagram.com/v1/users/search?q=' + settings.username + '&client_id=' + settings.client_id,
success: function (data) {
if (data.meta.error_message) {
var error_message = 'Error: ' + data.meta.error_message.toLowerCase();
$button.text(error_message).addClass('error');
return false;
}
if (data.data.length) {
var num_items = data.data.length - 1;
$.each(data.data, function (i, user) {
if (settings.username === user.username) {
var user_id = user.id;
getPhotos(user_id);
return false;
}
if (i === num_items) {
$button.text('Error: no users found').addClass('error');
}
});
} else {
$button.text('Error: no users found').addClass('error');
}
},
error: function () {
$button.text('Error: unknown').addClass('error');
}
});
} else if (settings.hashtag) {
getPhotos();
} else {
$button.text('Error: missing username or hashtag').addClass('error');
}
$button.click(function (e) {
e.preventDefault();
if (!$(this).is('.disabled, .error')) {
getPhotos();
}
});
$(window).on('load resize', resize);
};
}(jQuery));
If you need to see any of the other code please ask! Any help is much appreciated as you may have well guessed - I'm new to all of this
Thanks!
when you are calling the fancybox, images may not have been loaded to the DOM. call the fancybox plugin after the image load, not on the $(document).ready();
function renderPhotos(data) {
$.each(data.data, function (i, photo) {
photo = '<li class="photo"><img src="' + photo.images.standard_resolution.url.replace(/\\/, "") + '"></li>';
$photos.append(photo);
return i <= (settings.count);
});
$(".ins_popup").fancybox({
openEffect : 'fade',
closeEffect : 'fade'
});
}
Also I see in your sample website that you have included jquery twice in the page
<!-- Include jQuery -->
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
Remove the 2nd Jquery include. this might be the issue.
So I am able to retrieve the images from instagram but I want the individual images to go into my gallery container div which I got a problem with. I have directed the images to the class "html5gallery" but the images does not goes in like other image urls :
<!-- Reference to html5gallery.js -->
<script type="text/javascript" src="../html5gallery/html5gallery.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/jquery-instagram/0.2.2/jquery.instagram.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.0.min.js"></script>
<script>
(function ($) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
var imgURL = '';
for (var i = 0; i < numDisplay; i++) {
var gallery = document.getElementById("html5gallery");
var img = new Image();
img.onload = function() {
document.getElementById('gallery').appendChild(img);
};
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
alert(imgURL);
}
});
})(jQuery);
</script>
<div style="display:none;margin:0 auto; " class="html5gallery" data-skin="horizontal" data-width="1200" data-height="680" >
<!-- Add images to Gallery -->
<a href="#" onload="javascript:document.img.src='data.data[i].images.low_resolution.url'">
<img src="images/Tulip_small.jpg" alt="Tulips">
<img src="images/Colourful_Tulip_small.jpg" alt="Colourful Tulips">
<img src="images/Swan_small.jpg" alt="Swan on Lake">
<img src="images/Red_Tulip_small.jpg" alt="Red Tulips">
<img src="images/Sakura_Tree_small.jpg" alt="Sakura Trees">
<img src="http://img.youtube.com/vi/1oHWvFrpocY/2.jpg" alt="Youtube Video">
<!-- Add Youtube video to Gallery -->
<img src="http://img.youtube.com/vi/ofr5EE9GsUs/2.jpg" alt="Youtube Video">
<!-- Add Youtube video to Gallery -->
<img src="http://img.youtube.com/vi/9bZkp7q19f0/2.jpg" alt="Youtube Video">
</div>
Change the class attribute to id or add the id attribute id="html5gallery"
<div style="display:none;margin:0 auto; "
class="html5gallery" id="html5gallery"
data-skin="horizontal" data-width="1200"
data-height="680" >
EDIT:
Try this to append image
var imgURL = '';
var gallery = $("#html5gallery");
for (var i = 0; i < numDisplay; i++) {
var img = new Image();
img.onload = (function(im) {
return function () {
gallery.append(im);
}
})(img);
img.src = data.data[i].images.low_resolution.url;
imgURL += img.src + ' ';
$(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
}
I've never used the instagram API before, but I think this is what you want to achieve (code below). I've included both a Vanilla Javascript method as well as a jQuery method (so you can pick and use whichever one you prefer - vanilla is faster of course)
(function ($, window) {
var userId = "19410587";
var accessToken = "574298972.d868eb6.bab9c8fe820c4d4c80724edfb86236bd";
var numDisplay = "4";
// Define the gallery variable outside the for loop (performance)
// Vanilla JS
var galleryHTML = document.getElementById("html5gallery");
// jQuery
var $galleryHTML = $('#html5gallery');
// Moved the gallery outside of the for loop (performance, again)
var gallery = document.getElementById('gallery');
var insta = $('.insta');
// or var insta = document.getElementsByClassName('insta')[0] for vanilla JS
// create a function to do the fancy ajax
var fetchInstagram = function() {
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/users/"+userId+"/media/recent/?access_token="+accessToken,
success: function(data) {
for (var i = 0; i < numDisplay; i++) {
// I don't think you need the onload function here
// img.onload = function() {
// document.getElementById('gallery').appendChild(img);
// };
// Not sure what this is, but I don't think you need it (for what you want to do)
// $(".insta").append("<div class='instaBox'><a target='_blank' href='" + data.data[i].link +"'><img class='instagram-image' src='" + data.data[i].images.low_resolution.url +"' width='98' /></a></div>");
// Create the new image object
var newImage = document.createElement('img');
newImage.src = data.data[i].images.low_resolution.url;
// Insert the images into html5gallery
// Vanilla Javascript Way
// galleryHTML.appendChild(newImage);
// jQuery Way
// var $newImage = $(newImage);
// $galleryHTML.append($newImage);
}
}
});
};
// Making the function available in window for global use
window.fetchInstagram = fetchInstagram;
})(jQuery, window);
// Initiate the function
fetchInstagram();
// You can bind the function to other stuff like.. if you click a button
// $('#load-more').on('click', fetchInstagram);
I was able to get the 4 images to load in a div with the id of html5gallery on my end. Hope this helps!
If the human eye can only see 24fps or 30fps or more when playing a game or watching tv, I believe a programer can use less DIVs in HTML within the screen size, with a Javascript array of 3 million colors for a couple of DIVs and cheat it's position(because of our human eyes), based in a timer event with a bunch of frames per second than the ones I mentioned, example 1 millisecond. In my opinion this is something which I would like to test, if it's the question that drives us let the answer be our destination.
This is the fiddle so far: DEMO
<html>
<head>
<title></title>
<style>#placeDiv{position:absolute;left:0px;width:100px;height:100px;}
#placeDiv1{position:absolute;left:100px;width:100px;height:100px;}
#placeDiv2{position:absolute;left:200px;width:100px;height:100px;}
#b1{position:absolute;top:100px;left:0px}
#b2{position:absolute;top:100px;left:80px}
#b3{position:absolute;top:100px;left:170px}
#b4{position:absolute;top:100px;left:270px}
#b5{position:absolute;top:100px;left:320px}
</style>
</head>
<body>
<div id = "placeDiv">ok</div><div id = "placeDiv1">ok</div><div id = "placeDiv2">ok</div>
<button id="b1" onclick="forward()">Forward</button>
<button id="b2" onclick="backward()">Backward</button>
<button id="b3" onclick="skip2()">skip2</button>
<button id="b4" onclick="automatic()">auto</button>
<button id="b5" onclick="stop()">stop</button>
<script>
var myArray = ["black","yellow","green","red","blue","blue","black","gray"];
var myArray1 = ["yellow","blue","green","red","green","blue","black","gray"];
var myArray2 = ["yellow","blue","green","red","green","blue","black","gray"];
var i = 0;
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
forward=function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
document.getElementById("placeDiv2").style.backgroundColor = myArray2[i];
}; skip2=function(){
if(i == myArray.length-4)
{i+=2;alert("This is the iterator "+i)}else if(i==7){i=0}else{i=i+1;};
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
};
backward=function(){
if(i == 0)
{i=myArray.length-1;i=myArray1.length-1;}
else
{
i=i-1;
}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
//
}
var m=null;
automatic=function(){
clearInterval(m)
m = setInterval(function(){
if(i == myArray.length-1)
{i=0;}
else
{i=i+1;}
document.getElementById("placeDiv1").style.backgroundColor = myArray1[i];
document.getElementById("placeDiv").style.backgroundColor = myArray[i];
},1);
function b(x,y){
var a =setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if (x==100){d();clearInterval(a);}},10);
function d(){var z = setInterval(function(){document.getElementById("placeDiv").style.left=x--+"px";if (x==0){c();clearInterval(z);}},10);}
function c(){var g = setInterval(function(){document.getElementById("placeDiv").style.left=x+++"px";if(x==100){d();clearInterval(g)}},10)};
//Aqui uma copia.
var v =setInterval(function(){document.getElementById("placeDiv").style.top=y+++"px";if (y==100){h();clearInterval(v);}},10);
function h(){var l = setInterval(function( {document.getElementById("placeDiv").style.top=y--+"px";if (y==0){ok();clearInterval(l);}},10);}
function ok(){var ja = setInterval(function( {document.getElementById("placeDiv").style.top=y+++"px";if(y==100 {h();clearInterval(ja)}},10)};
}
b(0,0);
stop=function(){clearInterval(m)};
};
</script>
</body>
</html>