Javascript, jquery for Owl Carousel: rearrange conditions, change items - javascript

On this page, that I uploaded through https://mappingforyou.eu/fusion/ , Owl Carousel calls on Flickr to provide some photos according to a list of National Parks, in the variable "cached", and the caption is the National park name
I would like to remove any reference to these parks and instead, add each item of photos2, with the jpg in "photo" and the caption in "caption", in that carousel which seems to bein the buildhtml function, but it has a parkname value and i have several values to provide.
So far, I'm very unsuccessful. I have trouble too, understanding some things in this code.
If the provided info isn't enough, or well written, please ask some additional info and I'd be glad to edit my question, with your help.
var photos;
var gallery_items;
function callFlickr(f, parkName) {
var bbox = turf.extent(f.geometry).join(",");
var tags = parkName.split(" ");
tags.push("park");
tags.push("national");
tags = tags.join(",");
$.ajax({
url : flickr_config.url,
//jsonp : "jsonFlickrApi",
dataType : 'json',
data : {
api_key : flickr_config.key,
tags : tags,
bbox : bbox,
format : 'json',
method : 'flickr.photos.search',
per_page : flickr_config.maxNumImages,
nojsoncallback : 1
}
}).done(function (resp) {
queue_length += 1;
if(resp.stat !== "ok") {
if(queue_length == current_req_length) {
buildHtml(parkName)
}
return;
}
photos = [];
$.each(resp.photos.photo, function (i, v) {
photos.push("https://farm" + v.farm + ".staticflickr.com/" + v.server + "/" + v.id + "_" + v.secret + "_n.jpg");
});
// add to cache
cached[parkName] = photos;
current_gallery[parkName] = photos;
if(queue_length == current_req_length) {
buildHtml(parkName);
}
});
}
// builds html for carousel
function buildHtml() {
// var gallery_items;
var gallery_container = $("<div />", {
id : 'owl-slider',
class : 'own-carousel'
});
var list = [];
$.each(current_gallery, function (park, photos) {
list.push("<a class='park-item' href='' target='_blank'>" + park + "</a>");
$.each(photos, function (idx, photo) {
var div = $("<div />", {
class : 'thumbnail'
});
div.on('mouseover', function (e) {
highlightPark(park);
});
div.on('mouseout', function (e) {
$.each(np_geo.getLayers(), function (i, l) {
l.setStyle(style());
});
});
var title = $("<span />", {
html : "<h2><span class='glyphicon glyphicon-globe inverse'></span> " + park + " National Park</h2>",
class : 'parkname-title'
});
var fullPhoto = photo.replace("n.jpg", "b.jpg");
var link = $("<a />", {
"data-lightbox" : "image-" + idx,
"data-title" : park + " (courtesy of Flickr)",
href : fullPhoto
});
var img = $("<img />", {
src : photo
});
link.append(img);
div.append(link);
div.append(title);
gallery_container.append(div);
});
});
list = list.join(' | ');
$("#parkslist").html(list);
$(".park-item").on('click', function (e) {
e.preventDefault();
highlightPark(e.target.text);
})
$("#slider").empty();
$("#slider").append(gallery_container);
$("#owl-slider").owlCarousel({
margin : 10,
autoWidth : true,
stagePadding : 50
});
}

Related

YouTube API --- next video autoplay?

I have a YouTube API working for fetching and listing to video, when user clicks on thumbnail they get the video autoplay perfectly, but I would like when the first video is finished, the next video from my list autoplays also.
I've looked on Stack Overflow but haven't found one that fits my needs. Here is the code:
// Searchbar Handler
$(function () {
var searchField = $('#query');
var icon = $('#search-btn');
// Focus Event Handler
$(searchField).on('focus', function () {
$(this).animate({
width: '100%' },
400);
$(icon).animate({
right: '10px' },
400);
});
// Blur Event Handler
$(searchField).on('blur', function () {
if (searchField.val() == '') {
$(searchField).animate({
width: '45%' },
400, function () {});
$(icon).animate({
right: '360px' },
400, function () {});
}
});
$('#search-form').submit(function (e) {
e.preventDefault();
});
});
function search() {
// Clear Results
$('#results').html('');
$('#buttons').html('');
// Get Form Input
q = $('#query').val();
// Run GET Request on API********************************
$.get(
"https://www.googleapis.com/youtube/v3/search?maxResults=**", {
part: 'snippet, id',
q: q+'********',
fs:1,
hd:1,
type: 'video',
videoCategoryId :'***',
key: 'your api key' },
function (data) {
var nextPageToken = data.nextPageToken;
var prevPageToken = data.prevPageToken;
// Log Data
console.log(data);
$.each(data.items, function (i, item) {
// Get Output****
var output = getOutput(item);
// Display Results*****
$('#results').append(output);
});
var buttons = getButtons(prevPageToken, nextPageToken);
// Display Buttons
$('#buttons').append(buttons);
});
}
///////////////////////////////////////////////////////////////
// Next Page Function
function nextPage() {
var token = $('#next-button').data('token');
var q = $('#next-button').data('query');
// Clear Results
$('#results').html('');
$('#buttons').html('');
// Get Form Input
q = $('#query').val();
// Run GET Request on API
$.get(
"https://www.googleapis.com/youtube/v3/search?maxResults=***", {
part: 'snippet, id',
q: '***********',
fs:1,
hd:1,
pageToken: token,
type: 'video',
videoCategoryId : '*****',
key: 'your api key' },
function (data) {
var nextPageToken = data.nextPageToken;
var prevPageToken = data.prevPageToken;
// Log Data
console.log(data);
$.each(data.items, function (i, item) {
// Get Output
var output = getOutput(item);
// Display Results
$('#results').append(output);
});
var buttons = getButtons(prevPageToken, nextPageToken);
// Display Buttons
$('#buttons').append(buttons);
});
}
// Prev Page Function
function prevPage() {
var token = $('#prev-button').data('token');
var q = $('#prev-button').data('query');
// Clear Results
$('#results').html('');
$('#buttons').html('');
// Get Form Input
q = $('#query').val();
// Run GET Request on API
$.get(
"https://www.googleapis.com/youtube/v3/search?maxResults=***", {
part: 'snippet, id',
q: **********,
fs:1,
hd:1,
pageToken: token,
type: 'video',
videoCategoryId : '*****',
key: 'your api key' },
function (data) {
var nextPageToken = data.nextPageToken;
var prevPageToken = data.prevPageToken;
// Log Data
console.log(data);
$.each(data.items, function (i, item) {
// Get Output
var output = getOutput(item);
// Display Results
$('#results').append(output);
});
var buttons = getButtons(prevPageToken, nextPageToken);
// Display Buttons
$('#buttons').append(buttons);
});
}
// Build Output**********************************************
function getOutput(item) {
var videoId = item.id.videoId;
var title = item.snippet.title.substring(0, 33);
/*var description = item.snippet.description.substring(0, 20);*/
var thumb = item.snippet.thumbnails.high.url;
var channelTitle = item.snippet.channelTitle;
var videoDate = item.snippet.publishedAt;
// Build Output String**************************************
var output = '<li>' +
'<a target="mainVid" href="https://www.youtube.com/embed/' + videoId + '/?autoplay=1&modestbranding=1&rel=0"><img src="' + thumb + '"></a>' +
'<h3><a target="mainVid" href="https://www.youtube.com/embed/' + videoId + '/?autoplay=1&modestbranding=1&rel=0">' + title + '</a></h3>' +
'<p>' + '</p>' +
'</li>' +
'<div class="clearfix"></div>' +
'';
return output;
}
// Build the buttons
function getButtons(prevPageToken, nextPageToken) {
if (!prevPageToken) {
var btnoutput = '<div class="button-container">' + '<button id="next-button" class="btn btn-primary" data-token="' + nextPageToken + '" data-query="' + q + '"' +
'onclick="nextPage();">Page Suiv</button></div>';
} else {
var btnoutput = '<div class="button-container">' +
'<button id="prev-button" class="btn btn-primary" data-token="' + prevPageToken + '" data-query="' + q + '"' +
'onclick="prevPage();">Page Préc</button>' +
'<button id="next-button" class="btn btn-primary" data-token="' + nextPageToken + '" data-query="' + q + '"' +
'onclick="nextPage();">Page Suiv</button></div>';
}
return btnoutput;
}
I know I need a function on an event but I don't know which one and where to place it.
have a look at this post Play next youtube src when the other one is finished Here is explained that you will need to use the youtube iFrame API (shared earlier) to be able to access the player events. This post also mentions in the post How to detect when a youtube video finishes playing? Here is a working example shared from 2012.
I don't write Javascript or have ever written something with the youtube API so I cannot give you a working example. But I'm sure with these posts and API docs you can find the answer you are seeking.
ok hi everyone !!!
here the solution with fancy box : add data-fancybox="video" on link to open
and give some instructions :
$('[data-fancybox]').fancybox({
infobar: false,
buttons: false,
afterLoad: function (instance, current) {
if (instance.group.length > 1 && current.$content) {
current.$content.append('<a data-fancybox-next class="button-next" href="javascript:;">→</a><a data-fancybox-previous class="button-previous" href="javascript:;">←</a>');
}
current.$content.append('<a data-fancybox-close class="button-close" href="javascript:;">×</a>');
} });
});
work very fine !!!!
thank for your help ...

delete from database with javascript

I added a delete function to a todo list app that i built. The delete function works; however, when I refresh the page all the items that i deleted come back. How can I remove the items permanently from the database?
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
//////this section works
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
///////this does not want to remove the item from the database
$.destroy("/tasks/" + itemId, {
_method: "destroy",
task: {
done: doneValue
}
});
});
$(function() {
// The taskHtml method takes in a JavaScript representation
// of the task and produces an HTML representation using
// <li> tags
function taskHtml(task) {
var checkedStatus = task.done ? "checked" : "";
var liClass = task.done ? "completed" : "";
var liElement = '<li id="listItem-' + task.id +'" class="' + liClass + '">' +
'<div class="view"><input class="toggle" type="checkbox"' +
" data-id='" + task.id + "'" +
checkedStatus +
'><label>' +
task.title +
// '<button class="deletebutton" type="button">Delete</button>' +
'</label></div></li>';
return liElement;
}
// toggleTask takes in an HTML representation of the
// an event that fires from an HTML representation of
// the toggle checkbox and performs an API request to toggle
// the value of the `done` field
function toggleTask(e) {
var itemId = $(e.target).data("id");
var doneValue = Boolean($(e.target).is(':checked'));
// still dont understand this
$.post("/tasks/" + itemId, {
_method: "PUT",
task: {
done: doneValue
}
}).success(function(data) {
var liHtml = taskHtml(data);
var $li = $("#listItem-" + data.id);
$li.replaceWith(liHtml);
$('.toggle').change(toggleTask);
} );
}
$.get("/tasks").success( function( data ) {
var htmlString = "";
$.each(data, function(index, task) {
htmlString += taskHtml(task);
});
var ulTodos = $('.todo-list');
ulTodos.html(htmlString);
$('.toggle').change(toggleTask);
});
$('#new-form').submit(function(event) {
event.preventDefault();
var textbox = $('.new-todo');
var payload = {
task: {
title: textbox.val()
}
};
$.post("/tasks", payload).success(function(data) {
var htmlString = taskHtml(data);
var ulTodos = $('.todo-list');
ulTodos.append(htmlString);
$('.toggle').click(toggleTask);
$('.new-todo').val('');
});
});
$("#deletebutton").on("click", function() {
$(".todo-list li.completed").remove()
var li_to_delete = $('.todo-list li.completed');
$.ajax({
type: 'DELETE',
url: "/tasks" + li_to_delete,
success: function(){
li_to_delete.remove();
}
});
});
});
i changed the code but im not sure how to properly extract the url.

Youtube API Get each playlist and its containing videos from channel

I'm trying to create a list of Youtube playlists and each list item to contain the playlist's videos as well.
Something like this (this would be a playlist section):
The issue I'm having is when calling the requestVideoPlaylist function inside the renderPlaylistSection I get undefined. However, if I call the requestVideoPlaylist with a given playlistId outside of the render... function the result gets returned correctly.
Please find my code on the following lines.
I've also made a reproduction on JSFiddle
// Retrieve the list of playlists
function requestPlaylists(channelId) {
playlistsContainer.html('');
var requestOptions = {
channelId: channelId,
part: 'snippet,contentDetails',
maxResults: 4
}
var request = gapi.client.youtube.playlists.list(requestOptions);
request.execute(function(response) {
var playlists = response.result.items;
if (playlists) {
$.each(playlists, function(index, item) {
renderPlaylistSection(playlistsContainer, item.id, item.snippet);
});
} else {
playlistsContainer.html('Sorry, you have no uploaded videos');
}
});
}
// Retrieve the list of videos in the specified playlist.
function requestVideoPlaylist(playlistId, pageToken) {
var requestOptions = {
playlistId: playlistId,
part: 'snippet,contentDetails',
maxResults: 5
};
if (pageToken) {
requestOptions.pageToken = pageToken;
}
var request = gapi.client.youtube.playlistItems.list(requestOptions);
request.execute(function(response) {
// Only show pagination buttons if there is a pagination token for the
// next or previous page of results.
nextPageToken = response.result.nextPageToken;
var nextVis = nextPageToken ? 'visible' : 'hidden';
$('.js-next-videos').css('visibility', nextVis);
prevPageToken = response.result.prevPageToken
var prevVis = prevPageToken ? 'visible' : 'hidden';
$('.js-prev-videos').css('visibility', prevVis);
var playlistItems = response.result.items;
if (playlistItems) {
$.each(playlistItems, function(index, item) {
if (this.snippet.thumbnails) {
renderVideoItem(item.snippet);
}
});
}
});
}
// Render playlist section
function renderPlaylistSection(container, playlistId, playlistSnippet) {
var title = playlistSnippet.title;
container.append(
'<div class="playlist"><h3>Playlist Title: ' + title + '</h3>' +
'<div class="row playlist-videos">' + requestVideoPlaylist(playlistId) + '</div></div>'
);
}
function renderVideoItem(videoSnippet) {
var title = videoSnippet.title;
var thumbnail = videoSnippet.thumbnails.medium.url;
return (
'<div class="thumb" style="overflow: hidden;">' +
'<img src="' + thumbnail + '">' +
'</div>'
);
}

Showing loading indication while loading XML

I have a webpage that I load my data from XML files to DIVs.
In this Example I have DIV with this attribute: class="Group";
Also this is my JS code:
$(document).ready(function () {
$.get(Root + "/Feed_Products/Groups", {}, function (xml) {
var output = '';
$('item', xml).each(function (i) {
var Name = $(this).find("Name").text();
var Id = $(this).find("Id").text();
var Link = Root + '/Group' + Id;
output += '' + Name + '';
});
$(".Group").append(output);
});
});
As you know, loading XML has delay and its not as fast as direct database request.
How can I show small loading GIF on each DIV that is loading XML?
Image: http://i.stack.imgur.com/BPWcg.png
$(document).ready(function () {
$(".Group").addClass("loading");
$.get(Root + "/Feed_Products/Groups", {}, function (xml) {
var output = '';
$('item', xml).each(function (i) {
var Name = $(this).find("Name").text();
var Id = $(this).find("Id").text();
var Link = Root + '/Group' + Id;
output += '' + Name + '';
});
$(".Group").append(output).removeClass("loading");
});
});
Then in your css define :
.Group.loading{
background-image: url("yourGIF.gif");
/* other rules */
}

Jquery literally writes the word "false" when function returns no data

I have a jquery function to turn my links into google map links. My links are dynamic and pulled from db. So some of the links will be blank depending if that post has that data or not.
PROBLEM: If the post does not have data for that link (field), my function will litteraly write "False" on the front end instead of just being left blank (I want it to just be blank if there is no data.
I think it just needs to be made into an if / else statement but im not very good with jquery and need help
Here is the function: ( (retailers_init['full_address']) ) is the hook for the data)
$('address').each(function () {
var link = "<a href='http://maps.google.com/maps?q=" + encodeURIComponent(retailers_init['full_address']) + "' target='_blank'>" + (retailers_init['full_address']) + "</a>";
$(this).html(link);
});
And here is the larger function that this function (that changes (retailers_init['full_address']) to a google map link) resides in.
function init(retailer) {
var retailers_init = (typeof (retailer) != 'undefined') ? retailer : (typeof (retailers[0]) != 'undefined') ? retailers[0] : 'undefined';
if (typeof (retailers_init) !== 'undefined') {
var image = $('.storeinfo ._image');
var phone_number = $('.storeinfo ._phone_number');
var email = $('.storeinfo ._email');
var website = $('.storeinfo ._website');
var title = $('.storeinfo ._title');
var full_address = $('.storeinfo .full_address');
image.stop().animate({
'opacity': '0'
}, 100, function() {
image
.removeAttr('style')
.attr('src', image.attr('data-load'))
.addClass('loading')
.animate({
'opacity': '1'
}, 200);
});
$('<img/>').load(function() {
image.stop().animate({
'opacity': '0'
}, 200, function() {
image.removeClass('loading');
image.attr('src', retailers_init['image']);
setTimeout(function() {
image.css({'margin-top': '-' + (image.height() / 2) + 'px'});
image.animate({
'opacity': '1'
}, 200);
}, 100);
});
}).attr('src', retailers_init['image']);
title.html(retailers_init['title']);
full_address.html(retailers_init['full_address']);
phone_number.html(retailers_init['phone_number']);
email.attr('href', 'mailto:' + retailers_init['email']).html(retailers_init['email']);
website.attr('href', retailers_init['website']).html(retailers_init['website']);
$('address').each(function () {
var link = "<a href='http://maps.google.com/maps?q=" + encodeURIComponent(retailers_init['full_address']) + "' target='_blank'>" + (retailers_init['full_address']) + "</a>";
$(this).html(link);
});
}
}

Categories

Resources