Add <li> dynamically reading from a folder photoswipe purpose - html

Sorry for my English, I am a new to jquery mobile and only have basic knowledge about javascript languages in general; I was playing around with a single page website mobile ( I usually use Dreamweaver CS6) and I reached a good result with photoswipe and everything was good since I had just few images. I have added a lot of them so now I would get the images' link dynamically.
In short, I want to start from a folder on my ftp and read all images file within it and create the <li> items for each one. Can I make this job with jquery mobile or should I use a language like php or .Net
I have read some examples around here and on google but they didn't help me a lot, like this one, I am sure it could be an answer for me in it but I don't know how to start
http://docs.phonegap.com/en/2.4.0/cordova_file_file.md.html#DirectoryReader
Here some code I'm using:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.css" />
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.3.2/jquery.mobile-1.3.2.min.js"></script>
<!-- Librerie PhotoSwipe -->
<link rel="stylesheet" type="text/css" href="../PhotoSwipe/photoswipe.css">
<link rel="stylesheet" type="text/css" href="../PhotoSwipe/styles.css">
<script type="text/javascript" src="../PhotoSwipe/klass.min.js"></script>
<script type="text/javascript" src="../PhotoSwipe/code.photoswipe-3.0.5.min.js"></script>
<!-- End PhotoSwipe -->
<script type="text/javascript">
$(document).ready(function(){ var myPhotoSwipe = $("#Gallery a").photoSwipe({ enableMouseWheel: false , enableKeyboard: false, captionAndToolbarAutoHideDelay: 0 }); });
</script>
Then my page
<div data-role="page" id="page">
<div data-role="header">
<h1>Title of my Page</h1>
</div>
<div data-role="content">
<ul id="Gallery" class="gallery">
<li>
<a href="../Images/img04.jpg">
<img src="../Images/img04.jpg" alt=""></a>
</li>
</ul>
</div>
When i land on this page everything works fine. Shall I use something like this?
That I took from this website, can I use JSON to accede to my ftp folder and than cycle the content?
Should I put this in a function? If yes who is going to call it?
$("#Photos").live("pagebeforeshow", function(){
$("ul#PhotoList").children().remove('li');
var tag = MyTag
$.getJSON("https://api.instagram.com/v1/tags/" + tag + "/media/recent?callback=?&client_id=####",
function(data){
$.each(data.data, function(i,item){
$("ul#PhotoList").append('<li><img src="' + item.images.low_resolution.url + '" alt="' + item.caption.text + '" width="200" /></li>');
});
});
var photoSwipeInstance = $("ul#PhotoList a").photoSwipe();
});
Any help is appriciated, thank you in advance, I am sure my issue here is my limited knowledge.

You should use pageinit and pagebeforeshow Instead of $(document).ready. Also .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live(). http://api.jquery.com/live/
Append list Items:
$("#PhotoList").append('<li><a href="..
When you finish refresh the list to display your new list:
$('#PhotoList').listview('refresh');
Update:
I use php programs on my server in order to retrieve json strings. Something like this...
xhr = new XMLHttpRequest();
xhr.open("GET","http://192.168.100.2/sr/quotelisttest?name="+s,true);
xhr.send("");
xhr.onreadystatechange = function() {
if (xhr.readyState === 4){
alert(xhr.readyState);
alert(xhr.responseText);
var v = JSON.parse(xhr.responseText);

Related

How to include header/footer in a static website? [duplicate]

I want to create common header and footer pages that are included on several html pages.
I'd like to use javascript. Is there a way to do this using only html and JavaScript?
I want to load a header and footer page within another html page.
You can accomplish this with jquery.
Place this code in index.html
<html>
<head>
<title></title>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous">
</script>
<script>
$(function(){
$("#header").load("header.html");
$("#footer").load("footer.html");
});
</script>
</head>
<body>
<div id="header"></div>
<!--Remaining section-->
<div id="footer"></div>
</body>
</html>
and put this code in header.html and footer.html, at the same location as index.html
click here for google
Now, when you visit index.html, you should be able to click the link tags.
I add common parts as header and footer using Server Side Includes. No HTML and no JavaScript is needed. Instead, the webserver automatically adds the included code before doing anything else.
Just add the following line where you want to include your file:
<!--#include file="include_head.html" -->
Must you use html file structure with JavaScript? Have you considered using PHP instead so that you can use simple PHP include object?
If you convert the file names of your .html pages to .php - then at the top of each of your .php pages you can use one line of code to include the content from your header.php
<?php include('header.php'); ?>
Do the same in the footer of each page to include the content from your footer.php file
<?php include('footer.php'); ?>
No JavaScript / Jquery or additional included files required.
NB You could also convert your .html files to .php files using the following in your .htaccess file
# re-write html to php
RewriteRule ^(.*)\.html$ $1.php [L]
RewriteRule ^(.+)/$ http://%{HTTP_HOST}/$1 [R=301,L]
# re-write no extension to .php
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.php [NC,L]
You could also put: (load_essentials.js:)
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:you#you.com'>Contact Us</a> / "
+ "<a href='mailto:you#you.com'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
I tried this:
Create a file header.html like
<!-- Meta -->
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<!-- JS -->
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script type="text/javascript" src="js/lib/angular.min.js"></script>
<script type="text/javascript" src="js/lib/angular-resource.min.js"></script>
<script type="text/javascript" src="js/lib/angular-route.min.js"></script>
<link rel="stylesheet" href="css/bootstrap.min.css">
<title>Your application</title>
Now include header.html in your HTML pages like:
<head>
<script type="text/javascript" src="js/lib/jquery-1.11.1.min.js" ></script>
<script>
$(function(){ $("head").load("header.html") });
</script>
</head>
Works perfectly fine.
I've been working in C#/Razor and since I don't have IIS setup on my home laptop I looked for a javascript solution to load in views while creating static markup for our project.
I stumbled upon a website explaining methods of "ditching jquery," it demonstrates a method on the site does exactly what you're after in plain Jane javascript (reference link at the bottom of post). Be sure to investigate any security vulnerabilities and compatibility issues if you intend to use this in production. I am not, so I never looked into it myself.
JS Function
var getURL = function (url, success, error) {
if (!window.XMLHttpRequest) return;
var request = new XMLHttpRequest();
request.onreadystatechange = function () {
if (request.readyState === 4) {
if (request.status !== 200) {
if (error && typeof error === 'function') {
error(request.responseText, request);
}
return;
}
if (success && typeof success === 'function') {
success(request.responseText, request);
}
}
};
request.open('GET', url);
request.send();
};
Get the content
getURL(
'/views/header.html',
function (data) {
var el = document.createElement(el);
el.innerHTML = data;
var fetch = el.querySelector('#new-header');
var embed = document.querySelector('#header');
if (!fetch || !embed) return;
embed.innerHTML = fetch.innerHTML;
}
);
index.html
<!-- This element will be replaced with #new-header -->
<div id="header"></div>
views/header.html
<!-- This element will replace #header -->
<header id="new-header"></header>
The source is not my own, I'm merely referencing it as it's a good vanilla javascript solution to the OP. Original code lives here: http://gomakethings.com/ditching-jquery#get-html-from-another-page
The question asks about using only HTML and JavaScript. The problem is that a second request to the server using JavaScript or even jQuery (requesting the extra header.html "later") is:
Slow!
So, this is unacceptable in a production environment. The way to go is to include only one .js file and serve your HTML template using only this .js file. So, in your HTML you can have:
<script defer src="header.js"></script>
<header id="app-header"></header>
And then, in your header.js put your template. Use backticks for this HTML string:
let appHeader = `
<nav>
/*navigation or other html content here*/
</nav>
`;
document.getElementById("app-header").innerHTML = appHeader;
This has also the benefit, that you can change the content of your template dynamically if you need! (If you want your code clean, my recommendation is not to include any other code in this header.js file.)
Explanation about speed
In the HTTP/2 world, the web server "undestands" what additional files (.css, .js, etc) should be sent along with a specific .html, and sends them altogether in the initial response. But, if in your "original" .html you do not have this header.html file imported (because you intend to call it later with a script), it won't be sent initially. So, when your JavaScript/jQuery requests it (this will happen much later, when HTML and your JavaScript will get "interpreted"), your browser will send a second request to the server, wait for the answer, and then do its stuff... That's why this is slow. You can validate this, using any browser's developer tools, watching the header.html coming much later.
So, as a general advice (there are a lot of exceptions of course), import all your additional files in your original .html (or php) file if you care about speed. Use defer if needed. Do not import any files later using JavaScript.
I think, answers to this question are too old... currently some desktop and mobile browsers support HTML Templates for doing this.
I've built a little example:
Tested OK in Chrome 61.0, Opera 48.0, Opera Neon 1.0, Android Browser 6.0, Chrome Mobile 61.0 and Adblocker Browser 54.0
Tested KO in Safari 10.1, Firefox 56.0, Edge 38.14 and IE 11
More compatibility info in canisue.com
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>HTML Template Example</title>
<link rel="stylesheet" href="styles.css">
<link rel="import" href="autoload-template.html">
</head>
<body>
<div class="template-container">1</div>
<div class="template-container">2</div>
<div class="template-container">3</div>
<div class="template-container">4</div>
<div class="template-container">5</div>
</body>
</html>
autoload-template.html
<span id="template-content">
Template Hello World!
</span>
<script>
var me = document.currentScript.ownerDocument;
var post = me.querySelector( '#template-content' );
var container = document.querySelectorAll( '.template-container' );
//alert( container.length );
for(i=0; i<container.length ; i++) {
container[i].appendChild( post.cloneNode( true ) );
}
</script>
styles.css
#template-content {
color: red;
}
.template-container {
background-color: yellow;
color: blue;
}
Your can get more examples in this HTML5 Rocks post
Aloha from 2018. Unfortunately, I don't have anything cool or futuristic to share with you.
I did however want to point out to those who have commented that the jQuery load() method isn't working in the present are probably trying to use the method with local files without running a local web server. Doing so will throw the above mentioned "cross origin" error, which specifies that cross origin requests such as that made by the load method are only supported for protocol schemes like http, data, or https. (I'm assuming that you're not making an actual cross-origin request, i.e the header.html file is actually on the same domain as the page you're requesting it from)
So, if the accepted answer above isn't working for you, please make sure you're running a web server. The quickest and simplest way to do that if you're in a rush (and using a Mac, which has Python pre-installed) would be to spin up a simple Python http server. You can see how easy it is to do that here.
I hope this helps!
It is also possible to load scripts and links into the header.
I'll be adding it one of the examples above...
<!--load_essentials.js-->
document.write('<link rel="stylesheet" type="text/css" href="css/style.css" />');
document.write('<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />');
document.write('<script src="js/jquery.js" type="text/javascript"></script>');
document.getElementById("myHead").innerHTML =
"<span id='headerText'>Title</span>"
+ "<span id='headerSubtext'>Subtitle</span>";
document.getElementById("myNav").innerHTML =
"<ul id='navLinks'>"
+ "<li><a href='index.html'>Home</a></li>"
+ "<li><a href='about.html'>About</a>"
+ "<li><a href='donate.html'>Donate</a></li>"
+ "</ul>";
document.getElementById("myFooter").innerHTML =
"<p id='copyright'>Copyright © " + new Date().getFullYear() + " You. All"
+ " rights reserved.</p>"
+ "<p id='credits'>Layout by You</p>"
+ "<p id='contact'><a href='mailto:you#you.com'>Contact Us</a> / "
+ "<a href='mailto:you#you.com'>Report a problem.</a></p>";
<!--HTML-->
<header id="myHead"></header>
<nav id="myNav"></nav>
Content
<footer id="myFooter"></footer>
<script src="load_essentials.js"></script>
For a quick setup with plain javascript and because not answered yet, you could also use a .js file to store your redundant pieces (templates) of HTML inside a variable and insert it through innerHTML.
backticks are here the make it easy part this answer is about.
(you will also want to follow the link on that backticks SO Q/A if you read & test that answer).
example for a navbar that remains the same on each page :
<nav role="navigation">
<img src="image.png" alt="Home"/>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
</nav>
You can keep inside your HTMl :
<nav role="navigation"></nav>
and set inside nav.js file the content of <nav> as a variable in between backticks:
const nav= `
<img src="image.png" alt="Home"/>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
` ;
Now you have a small file from which you can retrieve a variable containing HTML. It looks very similar to include.php and can easily be updated without messing it up (what's inside the backticks).
You can now link that file like any other javascript file and innerHTML the var nav inside <nav role="navigation"></nav> via
let barnav = document.querySelector('nav[role="navigation"]');
barnav.innerHTML = nav;
If you add or remove pages, you only have to update once nav.js
basic HTML page can be :
// code standing inside nav.js for easy edit
const nav = `
<img src="image.png" alt="Home"/>
<a href="/about.html" >About</a>
<a href="/services.html" >Services</a>
<a href="/pricing.html" >Pricing</a>
<a href="/contact.html" >Contact Us</a>
`;
nav[role="navigation"] {
display: flex;
justify-content: space-around;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home</title>
<!-- update title if not home page -->
<meta name="description" content=" HTML5 ">
<meta name="author" content="MasterOfMyComputer">
<script src="nav.js"></script>
<!-- load an html template through a variable -->
<link rel="stylesheet" href="css/styles.css?v=1.0">
</head>
<body>
<nav role="navigation">
<!-- it will be loaded here -->
</nav>
<h1>Home</h1>
<!-- update h1 if not home page -->
<script>
// this part can also be part of nav.js
window.addEventListener('DOMContentLoaded', () => {
let barnav = document.querySelector('nav[role="navigation"]');
barnav.innerHTML = nav;
});
</script>
</body>
</html>
This quick example works & can be copy/paste then edited to change variable names and variable HTML content.
another approach made available since this question was first asked is to use reactrb-express (see http://reactrb.org) This will let you script in ruby on the client side, replacing your html code with react components written in ruby.
Use ajax
main.js
fetch("./includes/header.html")
.then(response => {
return response.text();
})
.then(data => {
document.querySelector("header").innerHTML = data;
});
fetch("./includes/footer.html")
.then(response => {
return response.text();
})
.then(data => {
document.querySelector("footer").innerHTML = data;
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Liks</title>
<link rel="stylesheet" href="css/styles.css">
</head>
<body>
<header></header>
<main></main>
<footer></footer>
<script src="/js/main.js"></script>
</body>
</html>
You can use object tag of HTML with out use of JavaScript.
<object data="header.html" type="text/html" height="auto"></object>
Credits : W3 Schools How to Include HTML
Save the HTML you want to include in an .html file:
Content.html
Google Maps<br>
Animated Buttons<br>
Modal Boxes<br>
Animations<br>
Progress Bars<br>
Hover Dropdowns<br>
Click Dropdowns<br>
Responsive Tables<br>
Include the HTML
Including HTML is done by using a w3-include-html attribute:
Example
<div w3-include-html="content.html"></div>
Add the JavaScript
HTML includes are done by JavaScript.
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
}
</script>
Call includeHTML() at the bottom of the page:
Example
<!DOCTYPE html>
<html>
<script>
function includeHTML() {
var z, i, elmnt, file, xhttp;
/*loop through a collection of all HTML elements:*/
z = document.getElementsByTagName("*");
for (i = 0; i < z.length; i++) {
elmnt = z[i];
/*search for elements with a certain atrribute:*/
file = elmnt.getAttribute("w3-include-html");
if (file) {
/*make an HTTP request using the attribute value as the file name:*/
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4) {
if (this.status == 200) {elmnt.innerHTML = this.responseText;}
if (this.status == 404) {elmnt.innerHTML = "Page not found.";}
/*remove the attribute, and call this function once more:*/
elmnt.removeAttribute("w3-include-html");
includeHTML();
}
}
xhttp.open("GET", file, true);
xhttp.send();
/*exit the function:*/
return;
}
}
};
</script>
<body>
<div w3-include-html="h1.html"></div>
<div w3-include-html="content.html"></div>
<script>
includeHTML();
</script>
</body>
</html>

Checking the internet connection and reading the files on/off line [duplicate]

I am linking to the jQuery Mobile stylesheet on a CDN and would like to fall back to my local version of the stylesheet if the CDN fails. For scripts the solution is well known:
<!-- Load jQuery and jQuery mobile with fall back to local server -->
<script src="http://code.jquery.com/jquery-1.6.3.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write(unescape("%3Cscript src='jquery-1.6.3.min.js'%3E"));
}
</script>
I would like to do something similar for a style sheet:
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css" />
I am not sure if a similar approach can be achieved because I am not sure whether the browser blocks in the same way when linking a script as it does when loading a script (maybe it is possible to load a stylesheet in a script tag and then inject it into the page) ?
So my question is: How do I ensure a stylesheet is loaded locally if a CDN fails ?
One could use onerror for that:
<link rel="stylesheet" href="cdn.css" onerror="this.onerror=null;this.href='local.css';" />
The this.onerror=null; is to avoid endless loops in case the fallback it self is not available. But it could also be used to have multiple fallbacks.
However, this currently only works in Firefox and Chrome.
Update: Meanwhile, this seems to be supported by all common browsers.
Not cross-browser tested but I think this will work. Will have to be after you load jquery though, or you'll have to rewrite it in plain Javascript.
<script type="text/javascript">
$.each(document.styleSheets, function(i,sheet){
if(sheet.href=='http://code.jquery.com/mobile/1.0b3/jquery.mobile-1.0b3.min.css') {
var rules = sheet.rules ? sheet.rules : sheet.cssRules;
if (rules.length == 0) {
$('<link rel="stylesheet" type="text/css" href="path/to/local/jquery.mobile-1.0b3.min.css" />').appendTo('head');
}
}
})
</script>
Assuming you are using the same CDN for css and jQuery, why not just do one test and catch it all??
<link href="//ajax.googleapis.com/ajax/libs/jqueryui/1/themes/start/jquery-ui.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>
<script type="text/javascript">
if (typeof jQuery == 'undefined') {
document.write(unescape('%3Clink rel="stylesheet" type="text/css" href="../../Content/jquery-ui-1.8.16.custom.css" /%3E'));
document.write(unescape('%3Cscript type="text/javascript" src="/jQuery/jquery-1.6.4.min.js" %3E%3C/script%3E'));
document.write(unescape('%3Cscript type="text/javascript" src="/jQuery/jquery-ui-1.8.16.custom.min.js" %3E%3C/script%3E'));
}
</script>
I guess the question is to detect whether a stylesheet is loaded or not. One possible approach is as follows:
1) Add a special rule to the end of your CSS file, like:
#foo { display: none !important; }
2) Add the corresponding div in your HTML:
<div id="foo"></div>
3) On document ready, check whether #foo is visible or not. If the stylesheet was loaded, it will not be visible.
Demo here -- loads jquery-ui smoothness theme; no rule is added to stylesheet.
this article suggests some solutions for the bootstrap css
http://eddmann.com/posts/providing-local-js-and-css-resources-for-cdn-fallbacks/
alternatively this works for fontawesome
<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
<script>
(function($){
var $span = $('<span class="fa" style="display:none"></span>').appendTo('body');
if ($span.css('fontFamily') !== 'FontAwesome' ) {
// Fallback Link
$('head').append('<link href="/css/font-awesome.min.css" rel="stylesheet">');
}
$span.remove();
})(jQuery);
</script>
You might be able to test for the existence of the stylesheet in document.styleSheets.
var rules = [];
if (document.styleSheets[1].cssRules)
rules = document.styleSheets[i].cssRules
else if (document.styleSheets[i].rules)
rule= document.styleSheets[i].rules
Test for something specific to the CSS file you're using.
Here's an extension to katy lavallee's answer. I've wrapped everything in self-executing function syntax to prevent variable collisions. I've also made the script non-specific to a single link. I.E., now any stylesheet link with a "data-fallback" url attribute will automatically be parsed. You don't have to hard-code the urls into this script like before. Note that this should be run at the end of the <head> element rather than at the end of the <body> element, otherwise it could cause FOUC.
http://jsfiddle.net/skibulk/jnfgyrLt/
<link rel="stylesheet" type="text/css" href="broken-link.css" data-fallback="broken-link2.css">
.
(function($){
var links = {};
$( "link[data-fallback]" ).each( function( index, link ) {
links[link.href] = link;
});
$.each( document.styleSheets, function(index, sheet) {
if(links[sheet.href]) {
var rules = sheet.rules ? sheet.rules : sheet.cssRules;
if (rules.length == 0) {
link = $(links[sheet.href]);
link.attr( 'href', link.attr("data-fallback") );
}
}
});
})(jQuery);
Do you really want to go down this javascript route to load CSS in case a CDN fails?
I haven't thought all the performance implications through but you're going to lose control of when the CSS is loaded and in general for page load performance, CSS is the first thing you want to download after the HTML.
Why not handle this at the infrastructure level - map your own domain name to the CDN, give it a short TTL, monitor the files on the CDN (e.g. using Watchmouse or something else), if CDN fails, change the DNS to backup site.
Other options that might help are "cache forever" on static content but there's no guarantee the browser will keep them of course or using the app-cache.
In reality as someone said at the top, if your CDN is unreliable get a new one
Andy
Look at these functions:
$.ajax({
url:'CSS URL HERE',
type:'HEAD',
error: function()
{
AddLocalCss();
},
success: function()
{
//file exists
}
});
And here is vanilla JavaScript version:
function UrlExists(url)
{
var http = new XMLHttpRequest();
http.open('HEAD', url, false);
http.send();
return http.status!=404;
}
if (!UrlExists('CSS URL HERE') {
AddLocalCss();
}
Now the actual function:
function AddLocalCss(){
document.write('<link rel="stylesheet" type="text/css" href=" LOCAL CSS URL HERE">')
}
Just make sure AddLocalCss is called in the head.
You might also consider using one of the following ways explained in this answer:
Load using AJAX
$.get(myStylesLocation, function(css)
{
$('<style type="text/css"></style>')
.html(css)
.appendTo("head");
});
Load using dynamically-created
$('<link rel="stylesheet" type="text/css" href="'+myStylesLocation+'" >')
.appendTo("head");
Load using dynamically-created <style>
$('<style type="text/css"></style>')
.html('#import url("' + myStylesLocation + '")')
.appendTo("head");
or
$('<style type="text/css">#import url("' + myStylesLocation + '")</style>')
.appendTo("head");
I'd probably use something like yepnope.js
yepnope([{
load: 'http:/­/ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js',
complete: function () {
if (!window.jQuery) {
yepnope('local/jquery.min.js');
}
}
}]);
Taken from the readme.
//(load your cdn lib here first)
<script>window.jQuery || document.write("<script src='//me.com/path/jquery-1.x.min.js'>\x3C/script>")</script>

How can I swap out YouTube thumbnails for my latest upload?

I'm wanting to create a "Latest Video" block on my website, but I only need the YouTube thumbnail image and MAYBE the title of the video. I found a method for doing an embed for the latest video itself, but I'm uncertain if I can modify it for just the thumbnail.
<!DOCTYPE html>
<html>
<head>
<title>YouTube Recent Upload Thing</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
</head>
<body>
<div id="static_video"></div>
<script type="text/javascript">
function showVideo(response) {
if(response.data && response.data.items) {
var items = response.data.items;
if(items.length>0) {
var item = items[0];
var videoid = "http://www.youtube.com/embed/"+item.id;
console.log("Latest ID: '"+videoid+"'");
var video = "<iframe width='420' height='315' src='"+videoid+"' frameborder='0' allowfullscreen></iframe>";
$('#static_video').html(video);
}
}
}
</script>
<script type="text/javascript" src="https://gdata.youtube.com/feeds/api/users/urusernamehere/uploads?max-results=1&orderby=published&v=2&alt=jsonc&callback=showVideo"></script>
</body>
</html>
Can this be repurposed for my idea? And how can I do it if it can't? I have basic HTML and CSS knowledge, with a very limited understanding of javascript and php. If I can just get something that will swap the thumbnail and ideally display the title, I can handle styling and implementation. Also interested in the same for specific playlists' most recent addition, but that doesn't have to happen.
Not sure if this is what you mean but you can try something like:
<div onclick="this.style.display='none'; this.nextSibling.style.display='block';"><img src="image.png" style="cursor:pointer" /></div><div style="display:none">
<!-- Embed code here -->
</div>

AngularJS read data from JSON

hello I am new on angular and i come again to have some help.
I try to get datas from a json file : teams.json but it doesn't work
my controller is like this :
app.controller('TeamController', ['$http', function($http){
var liste = this;
liste.teams = [];
$http.get('teams.json').success(function(data){
liste.teams = data;
});
}]);
and in my html :
<!DOCTYPE html>
<html ng-app="teamStats">
<head>
<link rel="stylesheet" href="style.css">
<script src="script.js"></script>
<script src="angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="TeamController">
<!--
%%%%%%%%%%%%%%%%%%%%%%%%%%% BODY CONTENT
-->
<div id="wrap" >
<div class="container">
<div >
<ul>
<li ng-repeat="team in liste.teams">{{team.name + team.win}}</li>
</ul>
</div>
</div>
</div>
<!--
%%%%%%%%%%%%%%%%%%%%%%%%%%% END OF BODY CONTENT
-->
</body>
</html>
Many thanks in advance ! hope someone see where i am wrong
I did a plunker for easier understanding
myPlunker
Best regards,
Vincent
Change your controller to this
app.controller('TeamController', ['$http', '$scope',
function($http, $scope) {
var liste = this;
$scope.liste = {};
$scope.liste.teams = [];
$http.get('teams.json').success(function(data) {
$scope.liste.teams = data;
});
}
]);
And fix your json file. You need to remove the additional ,s
Demo: http://plnkr.co/edit/jeHnvykYLwVZLsRLznRI?p=preview
Ok i think i know now why it doesn't work !! ng-repeat, ng-view, ng-include and others use AJAX to load templates. The problem is that the browser by default does not allow AJAX requests to files located on your local file system (for security reasons). Therefore you have two options:
Run local web server that will serve your files
Tell your browser to allow local files access
Thanks for help all !! Thanks to Vadim explanation !! And thanks a lot zsong ! :)

Foundation 4 Orbit Slider All Images at Once/Not Scrollable

I can't figure out why the slider doesn't perform exactly like the one on the documentation page here:
http://foundation.zurb.com/docs/components/orbit.html
Our site is
here:
Here's the code. I think that it is supposed to be this minimal markup and that the rest of the stuff is supposed to be added later:
<ul data-orbit>
<li>
<img src="img/sliders/lightcubebeta1000.png" >
<div class="orbit-caption">...</div>
</li>
<li>
<img src="img/sliders/hammertime1000.png">
<div class="orbit-caption">...</div>
</li>
<li>
<img src= "img/sliders/alarmclockbeta1000.png">
<div class="orbit-caption">...</div>
</li>
</ul>
Initialization of the Javascript:
<!-- Javascript for Orbit Image Slider -->
<script>
document.write('<script src=`javascripts/vendor/'
+ ('__proto__' in {} ? 'zepto' : 'jquery')
+ '.js><\/script>')
</script>
<script src= "javascripts/foundation/foundation.js"></script>
<script src= "javascripts/foundation/foundation.dropdown.js"></script>
<script src= "javascripts/foundation/foundation.section.js"></script>
<script src= "javascripts/foundation/foundation.topbar.js"></script>
<script src= "javascripts/foundation/foundation.orbit.js"></script>
<!-- Initialize Foundation -->
<script>
$(document).foundation('orbit', {
timer_speed: 10000,
pause_on_hover: true,
resume_on_mouseout: true,
animation_speed: 500,
bullets: true,
stack_on_small: true,
container_class: 'orbit-container',
stack_on_small_class: 'orbit-stack-on-small',
next_class: 'orbit-next',
prev_class: 'orbit-prev',
timer_container_class: 'orbit-timer',
timer_paused_class: 'paused',
timer_progress_class: 'orbit-progress',
slides_container_class: 'orbit-slides-container',
bullets_container_class: 'orbit-bullets',
bullets_active_class: 'active',
slide_number_class: 'orbit-slide-number',
caption_class: 'orbit-caption',
active_slide_class: 'active',
orbit_transition_class: 'orbit-transitioning'
});
</script>
Despite my best efforts to copy the example on the docs page, the orbit image slider displays all the images at once top to bottom with the bullets and the arrows. Did I make a mistake or is there something wrong with the example in the foundation 4 docs?
Thank You!
You seem to have failed to carefully follow the Javascript Installation section of Foundation documentation.
You missed at least two steps:
require jQuery;
initialize Foundation.
Also, the code you provided in the question is different from the code you have on the actual page. On the page you use <ul class= "data-orbit"> while the correct code is <ul data-orbit>.
Here's a demo of everything set up properly: http://jsbin.com/ixuluw/3/edit
Thank you lolmaus. It turned out that after changing the <ul class="data-orbit"> back to <ul data-orbit> and by changing:
<script>
document.write('<script src=/js/vendor/'
+ ('__proto__' in {} ? 'zepto' : 'jquery')
+ '.js><\/script>');
</script>
to
<script>
document.write('<script src=`javascripts/vendor/'
+ ('__proto__' in {} ? 'zepto' : 'jquery')
+ '.js><\/script>')
</script>
It then appears to load zepto or jquery correctly, along with the orbit script. I must have missed the change, because all the javascript files are in the new folder. I must have been quite tired. Thanks again!