This is about a Blogger template called Bloggertube
Its originally coded to embed youtube videos and grab url image and post the image thumbnail
I also modified to work with Dailymotion
But I'm pretty newbie at Javascript, and I'm trying to figure out how to make a condition to make them work at same time, and also add more sites in the future
function createVideoThumb refers to thumbnail creation
function createVideoThumb2 refers to player's embed code
The blogger post sintax is:
(youtube link)endofvid
[starttext]
(post text)
[endtext]
Youtube code:
function createVideoThumb(pID){
var div = document.getElementById(pID);
var summ = summary_noimg;
if (div.innerHTML.indexOf("http://www.youtube.com/watch?v=")!=-1){
var vidid = div.innerHTML.substring(div.innerHTML.indexOf("http://www.youtube.com/watch?v=")+31,div.innerHTML.indexOf("endofvid"));
}else {var vidid =""};
var postlink = div.innerHTML.substring(div.innerHTML.indexOf("[postlink]")+10,div.innerHTML.indexOf("[/postlink]"));
if (vidid ==""){var imgvid ='<img class="thumbnail" src="http://i195.photobucket.com/albums/z105/dantearaujo/novideo.png" width="'+img_thumb_width+'px" height="'+img_thumb_height+'px"/>';
}else{
var imgvid ='<img class=thumbnail src="http://img.youtube.com/vi/'+vidid+'/mqdefault.jpg" width="'+img_thumb_width+'px" height="'+img_thumb_height+'px"/>';
};
var summary = imgvid ;
div.innerHTML = summary;
}
function createVideoThumb2(pID){
var div = document.getElementById(pID);
var imgtag = "";
var summ = summary_noimg;
if (div.innerHTML.indexOf("http://www.youtube.com/watch?v=")!=-1){
var vidid = div.innerHTML.substring(div.innerHTML.indexOf("http://www.youtube.com/watch?v=")+31,div.innerHTML.indexOf("endofvid"));
}else {var vidid =""};
var textinside = div.innerHTML.substring(div.innerHTML.indexOf("[starttext]")+11,div.innerHTML.indexOf("[endtext]"));
var postlink = div.innerHTML.substring(div.innerHTML.indexOf("[postlink]")+10,div.innerHTML.indexOf("[/postlink]"));
var embedvid = "";
if (vidid!="") {
embedvid = '<object width="654" height="393"><param name="movie" value="http://www.youtube.com/v/'+ vidid + '&hl=en&fs=1&rel=0&autoplay=1"></param><param name="allowFullScreen" value="true"></param><param name="allowscriptaccess" value="always"></param><embed src="http://www.youtube.com/v/'+ vidid + '&hl=en&fs=1&rel=0&autoplay=1" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" width="654" height="393"></embed></object>'
}
var summary = embedvid + '<div class="content">' + textinside + '</div>';
div.innerHTML = summary;
}
Dailymotion code
function createVideoThumb(pID){
var div = document.getElementById(pID);
var summ = summary_noimg;
if (div.innerHTML.indexOf("http://www.dailymotion.com/video/")!=-1){
var vidid = div.innerHTML.substring(div.innerHTML.indexOf("http://www.dailymotion.com/video/")+33,div.innerHTML.indexOf("endofvid"));
}else {var vidid =""};
var postlink = div.innerHTML.substring(div.innerHTML.indexOf("[postlink]")+10,div.innerHTML.indexOf("[/postlink]"));
if (vidid ==""){var imgvid ='<img class="thumbnail" src="http://i195.photobucket.com/albums/z105/dantearaujo/novideo.png" width="'+img_thumb_width+'px" height="'+img_thumb_height+'px"/>';
}else{
var imgvid ='<img class=thumbnail src=" http://www.dailymotion.com/thumbnail/video/'+vidid+'" width="'+img_thumb_width+'px" height="'+img_thumb_height+'px"/>';
};
var summary = imgvid ;
div.innerHTML = summary;
}
function createVideoThumb2(pID){
var div = document.getElementById(pID);
var imgtag = "";
var summ = summary_noimg;
if (div.innerHTML.indexOf("http://www.dailymotion.com/video/")!=-1){
var vidid = div.innerHTML.substring(div.innerHTML.indexOf("http://www.dailymotion.com/video/")+33,div.innerHTML.indexOf("endofvid"));
}else {var vidid =""};
var textinside = div.innerHTML.substring(div.innerHTML.indexOf("[starttext]")+11,div.innerHTML.indexOf("[endtext]"));
var postlink = div.innerHTML.substring(div.innerHTML.indexOf("[postlink]")+10,div.innerHTML.indexOf("[/postlink]"));
var embedvid = "";
if (vidid!="") {
embedvid = '<iframe frameborder="0" width="654" height="393" src="//www.dailymotion.com/embed/video/'+ vidid +'" allowfullscreen></iframe>'
}
var summary = embedvid + '<div class="content">' + textinside + '</div>';
div.innerHTML = summary;
}
I think I understand where your problem is. The solution is to only have 2 functions: createVideoThumb and createVideoThumb2. In the start of the functions, make a check what the inner html contains. For example:
function createVideoThumb2(pID){
// Dailymotion
if (div.innerHTML.indexOf("http://www.dailymotion.com/video/")!=-1){
// Set specific local vars here
}
// Youtube
else if(div.innerHTML.indexOf("http://www.youtube.com/watch?v=")!=-1) {
// Set specific local vars here
}
// .... More providers
// Use specific local vars in the code below (I didnt edit anything below)
var div = document.getElementById(pID);
var imgtag = "";
var summ = summary_noimg;
if (div.innerHTML.indexOf("http://www.dailymotion.com/video/")!=-1){
var vidid = div.innerHTML.substring(div.innerHTML.indexOf("http://www.dailymotion.com/video/")+33,div.innerHTML.indexOf("endofvid"));
}else {var vidid =""};
var textinside = div.innerHTML.substring(div.innerHTML.indexOf("[starttext]")+11,div.innerHTML.indexOf("[endtext]"));
var postlink = div.innerHTML.substring(div.innerHTML.indexOf("[postlink]")+10,div.innerHTML.indexOf("[/postlink]"));
var embedvid = "";
if (vidid!="") {
embedvid = '<iframe frameborder="0" width="654" height="393" src="//www.dailymotion.com/embed/video/'+ vidid +'" allowfullscreen></iframe>'
}
var summary = embedvid + '<div class="content">' + textinside + '</div>';
div.innerHTML = summary;
}
You can do this for both functions, and then use the vars throughout the rest of the function. Vars should be like iframeWidth, iframeHeight,... and so on, whatever you need customised for each provider.
Related
I have written this code which is supposed to print the information from the xml file into a list for each faculty member. I want to eventually place all of these into a table, but need to know how to print them to the screen first.
function init() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.responseXML);
var faculty = this.responseXML.getElementsByTagName("faculty");
var strOut = "<ul>";
for (i = 0; i < faculty.length; i++) {
var name = faculty[i].getElementsByTagName("name")[0].innerHTML;
var title = faculty[i].getElementsByTagName("title")[0].innerHTML;
var office = faculty[i].getElementsByTagName("office")[0].innerHTML;
var phone = faculty[i].getElementsByTagName("phone")[0].innerHTML;
var email = faculty[i].getElementsByTagName("email")[0].innerHTML;
strOut += "<li><a href = " + name + title + "</a></li>";
}
strOut += "<ul>";
document.getElementById("output").innerHTML = strOut;
}
};
xhttp.open("GET", "faculty.xml", true);
xhttp.send();
}
window.onload = init;
Here is the XML file:
<facultyInfo>
<faculty>
<name>Prof A</name>
<title>Professor and Program Coordinator</title>
<office>CI 555</office>
<phone>(999-999-9999</phone>
<email>ProfA#school.edu</email>
</faculty>
<faculty>
<name>Prof B</name>
<title>Visiting Professor</title>
<office>CI 333</office>
<phone>999-999-9999</phone>
<email>ProfB#school.edu</email>
</faculty>
</facultyInfo>
This line:
strOut += "<li><a href = " + name + title + "</a></li>";
... is both malformed and probably not what you intended. Between the missing quotes for the href attribute, missing the ">" to close off the <a> start, and not putting any text in between <a></a>, this results in a link tag where the link destination (href) is set, but the actual text to show to the user is not set. I don't see any links in your XML (maybe that is for the future), so for now you probably want something like this:
strOut += '<li>' + name + ', ' + title + '</li>';
Here is a quick demo with your XML input:
<div id="output"></div>
<script>
var xmlString = '<facultyInfo> <faculty> <name>Prof A</name> <title>Professor and Program Coordinator</title> <office>CI 555</office> <phone>(999-999-9999</phone> <email>ProfA#school.edu</email> </faculty> <faculty> <name>Prof B</name> <title>Visiting Professor</title> <office>CI 333</office> <phone>999-999-9999</phone> <email>ProfB#school.edu</email> </faculty> </facultyInfo>';
var xmlDoc = (new DOMParser()).parseFromString(xmlString,'text/xml');
// var faculty = this.responseXML.getElementsByTagName("faculty");
var faculty = xmlDoc.getElementsByTagName("faculty");
var strOut = "<ul>";
for (i = 0; i < faculty.length; i++){
var name = faculty[i].getElementsByTagName("name")[0].innerHTML;
var title = faculty[i].getElementsByTagName("title")[0].innerHTML;
var office = faculty[i].getElementsByTagName("office")[0].innerHTML;
var phone = faculty[i].getElementsByTagName("phone")[0].innerHTML;
var email = faculty[i].getElementsByTagName("email")[0].innerHTML;
strOut += '<li>' + name + ', ' + title + '</li>';
}
strOut += "<ul>";
document.getElementById("output").innerHTML = strOut;
</script>
I am working on a website and I am looking to make the recipes pages dynamic. I created a JSON test database, created a JS file that retrieves values from the JSON file and displays them in appropriate divs on the page.
What i want to do is be able to choose the respectful JSON for each recipe and display it on the same page when a user clicks a link in the sidebar without having to create a ton of blank HTML pages with the same divs.
Below is my code. Hoping someone can help guide me thanks!
(function() {
'use strict';
var url = 'my json url';
$.getJSON(url, function(json) {
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
//retrieve values from dataArray
$.each(data[0], function (i, item) {
title += '<h1>' + item.recipeName + '</h1>';
image += '<img src="' + item.imageURL + '">';
directions += '<p>' + item.directions + '</p>';
prep += '<strong>' + item.prepTime + '</strong>';
cook += '<strong>' + item.cookTime + '</strong>';
serve += '<strong>' + item.servInfo + '</strong>';
});
//append results to div
$('#recipeTitle').html(title);
$('#recipeImage').html(image);
$('#recipeDirections').html(directions);
$('#recipePrep').html(prep);
$('#recipeCook').html(cook);
$('#recipeServes').html(serve);
var ul = $('<ul class="nav nav-stacked">').appendTo('#recipeIngredients');
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
});
})();
new code`(function() {
function callback(json){
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
//retrieve values from dataArray
$.each(data[0], function (i, item) {
title += '<h1>' + item.recipeName + '</h1>';
image += '<img src="' + item.imageURL + '">';
directions += '<p>' + item.directions + '</p>';
prep += '<strong>' + item.prepTime + '</strong>';
cook += '<strong>' + item.cookTime + '</strong>';
serve += '<strong>' + item.servInfo + '</strong>';
});
//append results to div
$('#recipeTitle').html(title);
$('#recipeImage').html(image);
$('#recipeDirections').html(directions);
$('#recipePrep').html(prep);
$('#recipeCook').html(cook);
$('#recipeServes').html(serve);
var ul = $('<ul class="nav nav-stacked">').appendTo('#recipeIngredients');
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
}
$('#pasta').click(function(){
$('#recipeIngredients').empty();
//get the url from click coresponding to the item
$.getJSON(url,callback);
});
//intially load the recipies with the URL
var url = '';
$.getJSON(url,callback);
})();`
to achieve code reusability , try calling the $.getJSON() with a reusable function (callback) on click of the link in the sidebar
(function() {
function callback(json){
//store json data into variable
var data = (json);
//store data in empty string
var title = '';
var image = '';
var directions = '';
var prep = '';
var cook = '';
var serve = '';
.... //rest of the code
...
$.each(data[0][0].ingredients, function(i, item) {
ul.append($(document.createElement('li')).text(item));
});
}
$('.sidebarLink').click(function(){
$('#recipeIngredients').empty()
//get the url from click coresponding to the item
$.getJSON(url,callback);
});
//intially load the recipies with the URL
var url = 'my json url';
$.getJSON(url,callback);
})();
I've got this code which basically.. On click of a div, it loads up the paragraph and inserts it into the twitch api url. The script should be working but what happens is after the fadeOut the div remains empty. The console returns the error that twitchData isn't defined, but it is.
So it should work like this: Click on the div -> Understand which div was clicked -< fadeOut + empty() the div -> get the paragraph text -> replace it inside the twitchApi link etcetera.
$('.games > div').click((e) => {
var gameDiv = $(this); // Get which div was clicked here
$('#twitch').children().fadeOut(500).promise().then(function() {
$('#twitch').empty();
$(function() {
var i = 0;
var gameName = $(e.target).text().replace(' ', '%20'); // Get the game name
console.log(gameName);
var twitchApi = "https://api.twitch.tv/kraken/streams?game=" +gameName; // Build the URL here
var twitchData;
$.getJSON(twitchApi, function(json) {
twitchData = json.streams;
setData()
});
});
function setData() {
var j = twitchData.length > (i + 9) ? (i + 9) : twitchData.length; for (; i < j; i++) {
var streamGame = twitchData[i].game;
var streamThumb = twitchData[i].preview.medium;
var streamVideo = twitchData[i].channel.name;
var img = $('<img style="width: 250px; height: 250px;" src="' + streamThumb + '"/>');
$('#twitch').append(img);
img.click(function() {
$('#twitch iframe').remove()
$('#twitch').append( '<iframe style="width: 600px;" src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
});
}
}
$('#load').click(function() {
setData();
});
});
});
This is a scope issue. You need to pass 'twitchData' into your setData function. Right now it is only defined within your click event.
$('.games > div').click((e) => {
var gameDiv = $(this); // Get which div was clicked here
$('#twitch').children().fadeOut(500).promise().then(function() {
$('#twitch').empty();
$(function() {
var i = 0;
var gameName = $(e.target).text().replace(' ', '%20'); // Get the game name
console.log(gameName);
var twitchApi = "https://api.twitch.tv/kraken/streams?game=" +gameName; // Build the URL here
$.getJSON(twitchApi, function(json) {
setData(json.streams)
});
});
function setData(twitchData) {
var j = twitchData.length > (i + 9) ? (i + 9) : twitchData.length; for (; i < j; i++) {
var streamGame = twitchData[i].game;
var streamThumb = twitchData[i].preview.medium;
var streamVideo = twitchData[i].channel.name;
var img = $('<img style="width: 250px; height: 250px;" src="' + streamThumb + '"/>');
$('#twitch').append(img);
img.click(function() {
$('#twitch iframe').remove()
$('#twitch').append( '<iframe style="width: 600px;" src="http://player.twitch.tv/?channel=' + streamVideo + '"></iframe>');
});
}
}
});
});
I have generated multiple barcodes using this code:
function getCode() {
var multipleCodes = document.getElementById('codeArea').value;
var eachLine = multipleCodes.split('\n');
console.log("eachLine = " + eachLine);
for (var i = 0; i < eachLine.length; i++) {
console.log("Inside loop: " + eachLine[i]);
var div = document.createElement('iframe');
div.innerHTML = "";
div.setAttribute('id', 'iFrameID' + i);
document.body.appendChild(div);
document.getElementById('iFrameID' + i).src = 'barCodeGenerator/generateBarCode.php?q=' + eachLine[i];
}
and trying to print it by using this method:
function printDiv(divName) {
var strName = document.getElementById("codeArea").value;
var imageId = document.getElementsByClassName('decoded');
var imagObject = new Image();
imagObject = imageId;
var originalImage = '<img id="imageViewer" src="' + imageSrc + '" style="padding-top: 20px" alt="' + imageSrc + '" />';
popup = window.open('', 'popup', 'toolbar=no,menubar=no,width=700,height=650');
popup.document.open();
popup.document.write("<html><head></head><body onload='print()'>");
popup.document.write(originalImage);
popup.document.write("</body></html>");
window.close('popup');
popup.document.close();
setTimeout(function () { popup.close(); }, 8000);
}
which only print single image by merging all barcodes.
How can i print them separately as multiple images.
Any help will be appreciated.
The most part of this code is irrelevant to your question. Consider removing your logs, the parts about showing popup and hiding it for more clearance.
Seems imageSrc variable in your code contains the source of one image, so you need to change your code by sending the array of image sources and iterating over it:
var originalImage = '';
// assuming imageSrc is an array of image sources
for (var i=; i < imageSrc.length; i++) {
// note that I'm changing the id of the image a litle bit to ensure it will remain unique
originalImage += '<img id="imageViewer' + i + '" src="' + imageSrc[i] + '" style="padding-top: 20px" alt="' + imageSrc[i] + '" />';
}
then the rest of your code must work.
I have this function which returns some XML datas from a foreign website :
function sendData()
{
var dev_statut = jQuery("select[name='statut']").val();
var dev_fdpaysid = jQuery("select[name='pays']").val();
var dev_fddeffet = jQuery("input[name='date_effet']").val();
var dev_fdnbadu = jQuery('select[name="nb_adultes"]').val();
var dev_fdnbenf = jQuery('select[name="nb_enfants"]').val();
var date_naiss_a_val = jQuery("input[name^=date_naissance_a]").map(function() {
var dev_date_naiss_a = 'dev_fadnaiss_';
return dev_date_naiss_a + this.id + '=' + this.value;
}).get().join('&');
var date_naiss_e_val = jQuery("input[name^=date_naissance_e]").map(function() {
var dev_date_naiss_e = 'dev_fadnaiss_';
return dev_date_naiss_e + this.id + '=' + this.value;
}).get().join('&');
var xdr = getXDomainRequest();
xdr.onload = function()
{
alert(xdr.responseXML);
var xml = xdr.responseXML;
var prod = xml.documentElement.getElementsByTagName("produit");
var proddata = [];
proddata.push('<ul>');
var len = prod.length;
for (var i = 0; i < len; i++) {
var nomprod = xml.getElementsByTagName('nomprod')[i].firstChild.nodeValue;
var url = xml.getElementsByTagName('url')[i].firstChild.nodeValue;
var desc = xml.getElementsByTagName('desc')[i].firstChild.nodeValue;
var texte = xml.getElementsByTagName('texte')[i].firstChild.nodeValue;
proddata.push("<li><div class='resultat_produit'>" + "<h1>" + nomprod + "</h1>" + "<p class='from_devis_desc'>" + desc + "</p>" + "<p class='form_devis_texte'>" + texte + "</p>" + "<a href='" + url + "'class='btn_url'>Faire un devis</a>" + "</div></li>");
}
proddata.push('</ul>');
jQuery('#mydiv2').append(proddata.join("\n"));
jQuery('.resultat_produit a').click(function(e)
{
e.preventDefault();
var href = jQuery(this).attr('href');
jQuery('#myDiv').empty();
jQuery('#myDiv').append('<iframe src="'+ href +'" scrolling="auto" width="960" height="100%"></iframe>');
});
}
xdr.open("GET", "http://www.MYURL.fr/page.php?dev_statut="+ dev_statut +"&dev_fdpaysid="+ dev_fdpaysid +"&dev_fddeffet="+ dev_fddeffet +"&dev_fdnbadu="+ dev_fdnbadu +"&dev_fdnbenf="+ dev_fdnbenf +"&"+ date_naiss_a_val +"&"+ date_naiss_e_val +"");
xdr.send();
}
It works fine on any major browsers (Chrome, FF, etc) but not on ... IE ! I've opened the console and it says : "DocumentElement is undefined ..."
I'm tired and can't fix that, any help will be very very appreciated !!