White space on layer update in 360 degree viewer - Leaflet - javascript

Good afternoon everyone!
I am trying to build a 360 degree viewer with zoom control. For that, I´m usig Leaflet. Everything works fine but layer update.
To change folder´s image container, I´m updating layer´s url, but in this change a white space appears for a while (few ms). I´ve been looking on Leaflet docs, internet, and trying on my own, but i´m unable to solve this.
Does anyone know any possible solution?
Thanks everyone for helping me!
PD: I can´t also give you images, but ím working with TileLayers.
CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Untitled Document</title>
<link href="style/jquery-ui.css"rel="stylesheet"/>
<link href="style/bootstrap.css" rel="stylesheet">
<link href="style/main.css" rel="stylesheet">
<link href="http://cdn.leafletjs.com/leaflet-0.7.4/leaflet.css" rel="stylesheet" />
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<img src="img norman foster/header.PNG" id="img_header" />
<div class="threesixty visor" id="image-map"></div>
<div id="slider"></div>
<div class="buttons">
<a class="btn custom_previous"><img src="src/images/rotateleftbutton.png" class="img-responsive" alt="Girar hacia la izquierda" /></a>
<a class="btn custom_next"><img src="src/images/rotaterightbutton.png" class="img-responsive" alt="Girar hacia la derecha" /></a>
</div>
<img src="img norman foster/footer.PNG" id="img_footer" />
<script src="http://cdn.leafletjs.com/leaflet-0.7.4/leaflet.js"></script>
<script src="js/L.TileLayer.Zoomify.js"></script>
<script src="js/jquery-1.11.3.min.js"></script>
<script src="js/jquery-ui.js"></script>
<script src="js/bootstrap.js"></script>
<script type="text/javascript">
window.onload = init;
var map = "";
var layer = "";
var oldSrc = "";
var newSrc = "";
var gui = "";
var path = "";
var imgcounter = 1;
var extension = "_img/";
var layers = new Array(80);
function init() {
oldSrc = './360/TNFF_0PO6055M_001/TNFF_0PO6055M_001-001_img/';
gui = oldSrc.indexOf("-");
path = oldSrc.substr(0, gui + 1);
getFiles();
//SLIDER
$(function() {
$("#slider").slider({
range : "min",
value : 1,
min : 1,
max : 80,
slide : function(event, ui) {
var photonumber = ui.value;
if (photonumber >= 1 && photonumber < 10) {
photonumber = "00" + String(photonumber);
newSrc = path + String(photonumber) + extension;
} else {
newSrc = path + "0" + String(photonumber) + extension;
}
oldSrc = newSrc;
imgcounter = parseInt(photonumber);
src = newSrc;
leafleft();
}
});
});
//BUTTONS
$('.custom_previous').bind('click', function(e) {
changeimageLeft();
});
$('.custom_next').bind('click', function(e) {
changeimageRight();
});
//LEAFLET
map = L.map('image-map').setView([0, 0], 2);
layer = L.tileLayer.zoomify(oldSrc, {
width : 8688,
height : 5792,
minZoom : 1,
maxZoom : 4,
attribution : 'LBNV',
unloadInvisibleTiles : true
}).addTo(map);
var southWest = map.getBounds().getSouthWest(),
northEast = map.getBounds().getNorthEast(),
bounds = L.latLngBounds(southWest, northEast);
map.setMaxBounds(bounds);
}
//URL CHANGE
function leafleft() {
layer.setUrl(newSrc);
oldSrc = newSrc;
}
//LEFT BUTTON
function changeimageLeft() {
if (imgcounter == 80) {
imgcounter = 1;
newSrc = path + "00" + imgcounter + extension;
} else if (imgcounter >= 1 && imgcounter < 10) {
imgcounter++;
if (imgcounter == 10) {
newSrc = path + "0" + imgcounter + extension;
} else {
newSrc = path + "00" + imgcounter + extension;
}
} else {
imgcounter++;
newSrc = path + "0" + imgcounter + extension;
}
common();
}
//RIGHT BUTTON
function changeimageRight() {
if (imgcounter == 1) {
imgcounter = 80;
newSrc = path + "0" + imgcounter + extension;
} else if (imgcounter >= 1 && imgcounter <= 10) {
imgcounter--;
if (imgcounter == 0) {
imgcounter = 1;
newSrc = path + "00" + imgcounter + extension;
} else if (imgcounter == 9) {
newSrc = path + "00" + imgcounter + extension;
} else {
newSrc = path + "00" + imgcounter + extension;
}
} else {
imgcounter--;
newSrc = path + "0" + imgcounter + extension;
}
common();
}
function common() {
layer.setUrl(newSrc);
oldSrc = newSrc;
$("#slider").slider('value', imgcounter);
}
</script>
</body>
</html>

The white screen transient that you see when changing the URL template of your Zoomify Tile Layer is very probably due to how Tile Layers (including the one from Zoomify plugin) behave when changing their URL: they redraw all their tiles using the new URL template, so there is a short duration when there is no image present.
You could mitigate this behaviour by simply using several Tile Layers and swapping them, instead of re-using the same one and changing its URL template. Then you would have like a Layers Control, but with your "Left" and "Right" buttons instead of one radio per layer.
However, you might still have a transient when the previous layer is swapped by the new one, so you might include a delay before actually removing the previous layer from the map.

Related

Chrome Extension JavaScript Error

I am trying to deploy a html+jss+css project of a pattern password as a chrome extension. On my local machine the code works as expected. However when I test it as a chrome extension, the box in which the pattern is to be entered is not displayed.
Code Below :
index.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=320; user-scalable=no; initial-scale=1.0; maximum-scale=1.0" />
<title>Pattern Lock Welcome Page</title>
<link rel="stylesheet" type="text/css" href="assets/css/main.css"/>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
<div id="jquery-script-menu">
<div class="jquery-script-clear"></div>
</div>
</div>
<h1 style="margin:150px auto 20px auto; text-align:center; color:#fff">Pattern Lock</h1>
<div class="maincontainer">
<h2 id="heading" class="heading">Please set your password</h2>
<div id="patterncontainer" class="patterncontainer">
</div>
</div>
</body>
<script src="js/script.js"></script>
</html>
welcome.html
<!doctype html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=320; user-scalable=no; initial-scale=1.0; maximum-scale=1.0" />
<title>Pattern Lock</title>
<link rel="stylesheet" type="text/css" href="assets/css/main.css"/>
</head>
<body>
<div class="maincontainer">
<h2 id="heading" class="heading">Homescreen</h2>
<button id="lockScreen" class="button-lockscreen" onclick="window.location= './index.html';">Lock Screen</a><br /><br />
<button id="resetPassword" class="button-reset" onclick="resetPassword()">Reset Password</a>
</div>
</body>
<script type="text/javascript" src="js/homepage.js"></script>
</html>
homepage.js
function resetPassword() {
console.log("sdfsdf");
if (localStorage.getItem("password")) {
alert("Pattern : "+localStorage.getItem("password"));
localStorage.removeItem("password");
successmessage("resetSuccess");
} else {
emptyPassword();
}
};
(function checkPassword(){
if (!localStorage.getItem("password")) {
emptyPassword();
}
}());
function successmessage(successcode) {
if (successcode == "resetSuccess") {
alert("Pattern Reset Success!");
}
location.reload();
};
function emptyPassword() {
document.getElementById("resetPassword").style.display = "none";
document.getElementById("lockScreen").innerHTML = "Set Password";
};
script.js
$(document).ready(function(){
var errorraised = false;
var passwordset = false;
var getClickStarted = false;
var autosubmit = true;
var password;
var centerX1;
var centerY1;
var curX = 0;
var curY = 0;
var getClickStarted = false;
var htmlLine;
var startpointnumber=0;
var endpointnumber=0;
(function checkIfPasswordIsSet() {
if (localStorage.getItem("password")) {
document.getElementById("heading").innerHTML = "Enter pattern to unlock screen";
passwordset = true;
}
else {
document.getElementById("heading").innerHTML = "Please set your pattern";
}
}());
(function generatebuttons(){
var patterncontainer = document.getElementById("patterncontainer");
for (var i = 1; i <=9; i++) {
var button = document.createElement("div");
button.className = "button";
button.id = "button" + i;
patterncontainer.appendChild(button);
startposition = document.getElementById("button" + i);
}
}());
(function main(){
if(!window.navigator.msPointerEnabled) {
$(".button").on("mousedown", function (event){
if(!getClickStarted){
getClickStarted = true;
var offset1 = $("#" + event.target.id).position();
centerX1 = offset1.left + $("#" + event.target.id).innerWidth()/2 + 20.5; //22.5 is the margin of the button class
centerY1 = offset1.top + $("#" + event.target.id).innerHeight()/2 + 20.5;
//console.log("centerX1 " + centerX1);
//console.log("centerY1 " + centerY1);
if (event && event.preventDefault){
event.preventDefault();
}
$("#" + event.target.id).removeClass("button").addClass("activebutton");
password = event.target.id.split("button").join("");
startpointnumber = event.target.id.split("button").join("");
//console.log("startpointnumber " + startpointnumber);
addline(startpointnumber, centerX1, centerY1); //initiating a moving line
}
});
$(document).bind("mousemove", function(event) {
if (getClickStarted){ //to avoid mousemove triggering before click
if (event && event.preventDefault){
event.preventDefault();
}
curX = event.clientX - $("#patterncontainer").offset().left;
curY = event.clientY - $("#patterncontainer").offset().top;
var width = Math.sqrt(Math.pow(curX - centerX1, 2) + Math.pow(curY - centerY1, 2)); //varying width and slope
var slope = Math.atan2(curY - centerY1, curX - centerX1)*180/3.14;
//setting varying width and slope to line
$("#line" + startpointnumber).css({"width": + width +"px", "height": "4px", "transform": "rotate(" + slope + "deg)", "-webkit-transform": "rotate(" + slope + "deg)", "-moz-transform": "rotate(" + slope + "deg)"});
//if button is found on the path
$(".button").bind("mouseover", function(e) {
endpointnumber = e.target.id.split("button").join("");
if (startpointnumber != endpointnumber) {
if (e && e.preventDefault){
e.preventDefault();
}
if (e.target.className == "button") {
$("#" + e.target.id).removeClass("button").addClass("activebutton");
} else {
$("#" + e.target.id).removeClass("activebutton").addClass("duplicatebutton");
}
password += e.target.id.split("button").join("");
// endpointnumber = e.target.id.split("button").join("");
$("#line" + startpointnumber).attr("id", "line" + startpointnumber + endpointnumber);
var offset2 = $("#" + e.target.id).position();
var centerX2 = offset2.left + $("#" + e.target.id).innerWidth()/2 + 20.5; //20.5 is the margin of activebutton class
var centerY2 = offset2.top + $("#" + e.target.id).innerHeight()/2 + 20.5;
var linewidth = Math.sqrt(Math.pow(centerX2 - centerX1, 2) + Math.pow(centerY2 - centerY1, 2));
var lineslope = Math.atan2(centerY2 - centerY1, centerX2 - centerX1)*180/3.14;
$("#line" + startpointnumber + endpointnumber).css({"width": + linewidth +"px", "transform": "rotate(" + lineslope + "deg)", "-webkit-transform": "rotate(" + lineslope + "deg)", "-moz-transform": "rotate(" + lineslope + "deg)"});
startpointnumber = endpointnumber;
centerX1 = centerX2;
centerY1 = centerY2;
addline(startpointnumber, centerX1, centerY1);
}
});
}
$("#patterncontainer").on("mouseup", function (event){
if(getClickStarted) {
if (event && event.preventDefault){
event.preventDefault();
}
$("#line" + startpointnumber).remove();
if (autosubmit) {
formsubmit();
}
}
getClickStarted = false;
});
});
} else {
alert ("INTERNET EXPLORER NOT SUPPORTED!!");
}
}());
function addline(startpointnumber, centerX1, centerY1){
var htmlLine = "<div id='line" + startpointnumber + "' class='line' style='position: absolute; top: " + centerY1 + "px; \
left: " + centerX1 + "px; -webkit-transform-origin: 2px 2px; -moz-transform-origin: 2.5% 50%; background-color: #FFF;'></div>"
$("#patterncontainer").append(htmlLine);
}
function formsubmit(){
var digits = getlength(password);
if(digits<5) {
raiseerror("lengthTooSmall");
}
checkduplicatedigits(password);
if (errorraised == false && passwordset == false) {
localStorage.setItem("password", password);
successmessage("patternStored");
}
else if ( errorraised == false && passwordset == true) {
if (localStorage.getItem("password") == password) {
successmessage("screenUnlocked");
window.location = "./welcome.html";
return false;
}
else {
raiseerror("IncorrectPattern");
}
}
};
function getlength(number) {
return number.toString().length;
};
function checkduplicatedigits(number) {
var digits = getlength(number);
numberstring = number.toString();
var numberarray = numberstring.split("");
var i; var j;
for (i = 0; i < digits-1; i++) {
for (j = i+1; j < digits; j++) {
if(numberarray[i] == numberarray[j]) {
raiseerror("repeatedEntry");
}
}
}
};
function successmessage(successcode) {
if(successcode == "screenUnlocked") {
alert("You have unlocked the screen!");
}
if (successcode == "patternStored") {
alert("Your pattern is stored. Thanks.");
passwordset = true;
}
if (successcode == "Success") {
alert("Pattern Reset Success!");
}
location.reload();
};
function raiseerror(errorcode) {
if(!errorraised){
errorraised = true;
if (errorcode == "lengthTooSmall") {
alert("The pattern is too short. Please try again.");
}
if (errorcode == "repeatedEntry") {
alert("You cannot use the same number twice. Please try again.");
}
if (errorcode == "IncorrectPattern") {
alert("The entered pattern in incorrect. Please try again.");
}
if (errorcode == "emptyPassword") {
alert("You did not set the password to reset it.");
}
location.reload();
}
};
});
and lastly this is my manifest.json :
{
"manifest_version": 2,
"name": "GRAphical Pass",
"description": "THIS IS SPARTA!!!!!!",
"version": "1.0",
"browser_action": {
"default_icon": "icon.png",
"default_popup": "index.html"
},
"permissions": [
"activeTab"
]
}
Any help would be much appreciated. Thanks :)
Expected(this is what I get on my machine)
But deploying it as an extension :
this is what I get
I suggest removing : $(document).ready(function(){
from your scripts and adding
"content_scripts": [
{
"matches": [
"<all_urls>"
],
"js": ["homepage.js","script.js"]
}
],
to your manifest along with the following CSP :
"content_security_policy": "script-src 'self' https://code.jquery.com; object-src 'self'"

Dynamic video Quiz in Javascript

I have 10 YouTube links and I want to be able to move to the next video by pressing the next button.
My code:
var videoLinks = ["https://www.youtube.com/embed/QIMo0jFbfQs", "http://www.youtube.com/v/L8NGOUrw8UU"];
var v = 0;
$("#next").on('click', function(){
next() + 1;
function next(){
if(v == videoLinks.length){
//v = 0;
}
$(".content").html(" <iframe src= ' " + videoLinks[v] + "'> "+ "</iframe>");
}
});
Note: I only included 2 links for testing.
You basically need a way to keep track of the vid count. Local Storage would be good for this. The button would increment the video counter and reset the value if you reached the end. The counter would be a reference to the video source value.
Use a simple replace to change the video source, embed the video, and then increment the counter.
It can be seen here: https://jsbin.com/dehoxo/edit?html,js,console,output
$(document).ready(function(){
$('#nextBtn').click(function(e){
e.preventDefault();
alert();
var vidIndex = parseInt(localStorage.getItem("vidIndex"));
var vids = ['https://www.youtube.com/embed/VT4gri_n0iM',
'https://www.youtube.com/embed/DWooSca2rCw',
'https://www.youtube.com/embed/MukFRbS_5Gw'];
var vidToken = '<iframe width="420" height="315" src="{{SRC}}" frameborder="0" allowfullscreen></iframe>';
if (vidIndex) {
if (vidIndex >= vids.length) {
vidIndex = 0;
}
}
else {
if (!vidIndex && vidIndex !==0) {
vidIndex = 0;
}
}
var currentVid = vidToken.replace('{{SRC}}', vids[vidIndex]);
$('#vidBox').html(currentVid);
$('#vidIndex').val(vidIndex);
vidIndex++;
localStorage.setItem('vidIndex', vidIndex);
});
});
The HTML
<!DOCTYPE html>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div id="vidBox">
NO VID
</div>
<button id="nextBtn">Next Vid</button>
<input id="vidIndex"/>
</body>
</html>
var videoLinks = [link1, link2, link3, ...];
var v = 0;
var iframe = $('iframe');
iframe.attr('src', videoLinks[0]);
$("#next").on('click', function(){
v++;
if(v >= videoLinks.length){
v = 0;
}
iframe.attr('src', videoLinks[v]);
});
Try this, it's a little more concise and easier to read:
var videoLinks = ["https://www.youtube.com/embed/QIMo0jFbfQs", "https://www.youtube.com/embed/L8NGOUrw8UU"];
var v = 0;
$("#next").on('click', function() {
$(".content").html(" <iframe src= ' " + videoLinks[v] + "'> " + "</iframe>");
v == videoLinks.length - 1 ? v = 0 : v++;
});
JSFiddle

Using Javascript to create a <link> element and then adding it to <head> section

What I am trying to accomplish is use javascript to write a element in the section. The link element that i'm trying to add looks like this
<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Oswald&effect=neon">
As requested I've posted the entire code.:
<!doctype html>
<html>
<head>
<title>Extra-Life Alerts</title>
<meta charset="utf-8">
<link href="singleAlert.css" rel="stylesheet">
<script>
var effect = $.url().param('effect');
var font = $.url().param('font');
/*
//document.getElementById("body").innerHTML = document.write('<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=' + font + '&effect=' + effect +'">');
//document.getElementById('head').innerHTML += '<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="' + font + '"&effect="' + effect + '"">';
//var stylesheetAdd = '<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="' + font + '"&effect="' + effect + '"">';
$(function() {
$('head').append('<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="' + font + '"&effect="' + effect + '""/>');
});
//var headID = document.getElementsByTagName("head")[0];
//$(headID).append('<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="' + font + '"&effect="' + effect + '"">');
//document.getElementById('#posts').className = 'font-effect-' + effect;
//document.getElementById('#posts').style.fontFamily = font;
//$("#posts").className("font-effect-" + effect).style.fontFamily(font); //= 'font-effect-' + effect;
//$("#posts").style.fontFamily(font); //= font;
//if (font) { $('.wf-active body, .wf-inactive body, #posts, body').css('font-family', font); }
//else{font="Impact"; $('.wf-active body, .wf-inactive body, #posts, body').css('font-family', font);}
*/
/*
//$('head').append('<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="' + font + '"&effect="' + effect + '""/>');
var stylesheetAdd = '<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family="'+font+'"&effect="'+effect+'"">';
//$('head').append('<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Oswald&effect=neon" />');
$(stylesheetAdd).appendTo(document.head);
*/
var headID = document.getElementsByTagName('head')[0];
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
link.href = 'http://fonts.googleapis.com/css?family=Oswald&effect=neon';
headID.appendChild(link);
/*
var link = $('<link />')
.appendTo(document.getElementsByTagName('head')[0])
.attr('rel', "stylesheet")
.attr('type', "text/css")
.attr('href', "http://fonts.googleapis.com/css?family=Oswald&effect=neon");
$(function(){
$(link);
});
*/
</script>
<!--<link rel="stylesheet" type="text/css" href="http://fonts.googleapis.com/css?family=Oswald&effect=neon">-->
</head>
<body>
<!--<script src="https://ajax.googleapis.com/ajax/libs/webfont/1.5.18/webfont.js"></script>-->
<script src="http://code.jquery.com/jquery-2.1.4.js"></script>
<script src="./javascript/jQuery-url-parser/2.3.1/purl.js"></script>
<script src="./javascript/dropzone/dropzone.js"></script>
<script>
var checkPriorDonorName = "prior name";
var getCurrentDonorName = "current name";
var checkPriorMessage = "prior message";
var getCurrentMessage = "current message";
function init() {
// Parse setup parameters.
var id = $.url().param('id');
var audio = $.url().param('audio');
var playAudio = document.createElement("AUDIO");
var xmlhttp = new XMLHttpRequest();
//var url = "http://2dc8c656ef.test-url.ws/tempDonations.txt";
var url = "http://www.extra-life.org/index.cfm?fuseaction=donorDrive.participantDonations&participantID=" + id + "&format=json";
xmlhttp.open("GET", url, true);
xmlhttp.send();
xmlhttp.onreadystatechange = function () {
getCurrentDonorName = xmlhttp.responseText;
getCurrentMessage = xmlhttp.responseText
};
getCurrentDonorName = JSON.parse(getCurrentDonorName);
getCurrentMessage = JSON.parse(getCurrentMessage);
xmlhttp.onreadystatechange = function () {
if ((xmlhttp.readyState == '4' && ( xmlhttp.status == '200' || xmlhttp.status == '204' )) &&
( checkPriorDonorName === "prior name" || getCurrentDonorName[0].donorName != checkPriorDonorName ) &&
( checkPriorMessage === "prior message") || getCurrentMessage[0].message != checkPriorMessage) {
extraLifeAlert(xmlhttp.responseText);
}
else
return;
};
/** Debugging steps
console.log("TEST BEGINNING NAME: Current: " + getCurrentDonorName[0].donorName + " | Prior: " + checkPriorDonorName);
console.log("TEST BEGINNING MESSAGE: Current: " + getCurrentMessage[0].message + " | Prior: " + checkPriorMessage);
*/
function extraLifeAlert(response) {
var donorName = JSON.parse(response);
var message = JSON.parse(response);
var donationAmount = JSON.parse(response);
if (donorName[0].donorName) {
$('#posts').find('.donorName').text(donorName[0].donorName);
}
if (donationAmount[0].donationAmount) {
$('#posts').find('.donationAmount').text(donationAmount[0].donationAmount);
}
if (message[0].message !== null) {
$('#posts').find('.message').text(message[0].message);
}
else {
$("#posts").find(".message").text("");
}
//setTimeout(function(){document.getElementById('#posts').attr('style', 'display: none')}, 0);
//setTimeout(function(){document.getElementById('#posts').attr('style', 'display: inline')}, 2000);
setTimeout(function () {
document.getElementById('#posts').style.display = 'none'
}, 0);
setTimeout(function () {
document.getElementById('#posts').style.display = 'inline'
}, 2000);
if (audio) {
playAudio.setAttribute("src", audio);
playAudio.load();
playAudio.play();
}
setTimeout(function () {
$("#posts").fadeIn(1000);
}, 1000);
setTimeout(function () {
$("#posts").fadeOut(1000);
}, 10000);
checkPriorDonorName = donorName[0].donorName;
checkPriorMessage = message[0].message;
}
}
/** Debugging steps
console.log("TEST END NAME: Current: " + getCurrentDonorName[0].donorName + " | Prior: " + checkPriorDonorName);
console.log("TEST END MESSAGE: Current: " + getCurrentMessage[0].message + " | Prior: " + checkPriorMessage);
*/
setInterval(init, 5000);
</script>
<div id="posts" style="display:none;font-family: Oswald;" class="font-effect-neon">
<div id="donationMessage"><span class="donorName"></span> Just donated $<span class="donationAmount"></span>.00 - <span class="message"></span></div>
</div>
<!--
<script>
$("#posts").addClass = ( "font-effect-" + effect );
/*.style.fontFamily(font);/*
.style.fontFamily(font); //= 'font-effect-' + effect;
$("#posts").find(".messages").append( $("#posts").hasClass("font-effect-neon").toString() );
*/
</script>
<!--
<script>
//var font = $.url().param('font');
//var reload = $.url().param('reload', false);
//var reloadTime = $.url().param('reloadTime');
/* Load Googles Webfont API*/
WebFont.load({
google: {
families: [font]
}
});
if (font) {
$(".wf-active body, .wf-inactive body, #posts").css("font-family", font);
}
else {
font = "Impact";
$(".wf-active body, .wf-inactive body, #posts").css("font-family", font);
}
//if(reload){setInterval(function(){location.reload(true);}, reloadTime);}
</script>-->
</body>
</html>
Opps think i cut and pasted out some stuff. So the only think that matters to get this google font+effects to work is that 1)you add the tag in the , 2)add the font & effect class in the section where your text is. For right now i'm manually entered it in for testing purposes. I plan to control all this via script so that the user can put the options in the url and have it work.
This is working :
var fontLoader = function (param) {
var link = document.createElement('link');
link.type = 'text/css';
link.rel = 'stylesheet';
//link.href = 'http://fonts.googleapis.com/css?family=Oswald&effect=neon';
document.head.appendChild(link);
link.href = 'http://fonts.googleapis.com/css?family=' + param.family + '&effect=' + param.effect;
};
fontLoader({
family: 'Oswald',
effect: 'neon'
});
.normal , .oswald {
padding : 3px;
margin : 3px;
color : #333;
border : solid 1px #CCC;
font-size : 2em;
}
.oswald {
font-family:'Oswald';
}
<div class='normal'>Normal Style</div>
<div class='oswald'>Oswald Style</div>
Just try this code at the end of your body.

Leaflet.js file runs in Safari but not Firefox, Chrome or IE

I am trying to create a mapping application that uses Leaflet.js to overlay GeoJson files on top of an OpenStreetMap file. The whole file is set out below and the GeoJson files are located on my GitHub page at https://github.com/ELamar/zoning
I can get the file to run in Safari, but can't get the file to run in Firefox, Chrome or IE. Nothing in the web inspectors for those browsers indicates any kind of error. The JSON files are very large (one is 9 MB and another about 6 MB), and I have nested the callbacks that read in the files. Could the issue be that is too much data to try to run in those browsers? If so, why would it run in Safari?
Any help would be greatly appreciated.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.css" />
</head>
<style>
svg {
position: relative;
}
</style>
<!--This file illustrates a map of Leon County Florida, complete with
2010 census block heatmap of population-->
<h1>This is a Draft Concept for a Collaborative Zoning Map.</h1>
<body>
<div id="map" style="width: 900px; height: 600px"></div>
<div id="detail" style="width: 30%; height: 600px"></div>
<script type="text/javascript" src="./d3.v3.js" charset="utf-8"></script>
<!--<script src="http://cdn.leafletjs.com/leaflet-0.7.2/leaflet.js"></script>-->
<script type="text/javascript" src="./leaflet.js"></script>
<!--<script src="http://labratrevenge.com/d3-tip/javascripts/d3.tip.v0.6.3.js"></script>-- >
<script src="./jquery-1.9.1.js"></script>
<!--<script src="./flare4.json"></script>-->
<!--<script src="./flare5.json"></script>-->
<script>
var map;
var ajaxRequest;
var plotlist;
var plotlayers=[];
function initmap() {
// set up the map
map = new L.Map('map');
// create the tile layer with correct attribution
//var osmUrl='http://www.openstreetmap.org/#map=13/30.4467/-84.3087';
//var osmUrl='http://osm.org/go/ZGUQ8RJ';
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 18, attribution: osmAttrib});
// start the map in Tallahassee Florida
//map.setView(new L.LatLng(30.4467,-84.3087),11); //sets view to Leon County
map.setView(new L.LatLng(30.4606,-84.2780),15); //sets view to MidTown Tallahassee
map.addLayer(osm);
}
initmap();
var osmUrl='http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png';
var osmAttrib='Map data © OpenStreetMap contributors';
var osm = new L.TileLayer(osmUrl, {minZoom: 8, maxZoom: 18, attribution: osmAttrib});
var baselayers = {"baselayer":osm};
function onEachFeature(feature, layer){
var med_age = feature.properties.median_age;
var str = med_age.toString();
layer.bindPopup("Media age: " + str);
// if (med_age > 0){
// layer.setStyle({fillOpacity:0.7});
// }
// else{
// layer.setStyle({fillOpacity:0});
// }
// [0,15,25,35,45,55,65,75,85])
if (med_age > 85){layer.setStyle({fillColor:"#03f",fillOpacity:0.9});}
else if (med_age > 75) {layer.setStyle({fillColor:"#08306B",fillOpacity:0.5});}
else if (med_age > 65) {layer.setStyle({fillColor:"#08519C",fillOpacity:0.5});}
else if (med_age > 55) {layer.setStyle({fillColor:"#2171B5",fillOpacity:0.5});}
else if (med_age > 45) {layer.setStyle({fillColor:"#4292C6",fillOpacity:0.5});}
else if (med_age > 35){layer.setStyle({fillColor:"#6BAED6",fillOpacity:0.5});}
else if (med_age > 25){layer.setStyle({fillColor:"#9ECAE1",fillOpacity:0.5});}
else if (med_age > 15){layer.setStyle({fillColor:"#C6DBEf",fillOpacity:0.5});}
else if (med_age > 0){layer.setStyle({fillColor:"#DEEBF7",fillOpacity:0.5});}
else {layer.setStyle({fillColor:"#f7fbff", fillOpacity:0});}
layer.on("mouseover", function (e) {
//var txt = layer.bindPopup(feature.properties.median_age);
// var text = layer.bindPopup(str);
var box = document.getElementById('detail');
//layer.bindPopup(feature.properties.median_age);
box.innerHTML = "Median age: " + str;
});
layer.on("mouseout", function (e) {
box = document.getElementById('detail');
box.innerHTML="";
});
}
function onEachFeature_zone(feature, layer){
layer.bindPopup("ID: " + feature.id + "<br>" + "Zoning: " + feature.properties.zoning);
}
function onEachFeature_active(feature, layer){
layer.bindPopup("ID: " + feature.id + "<br>" + "Zoning: " + feature.properties.zoning + "<br>" + "<a href='https://github.com/ELamar/Superior-Planning-PUD'>Comment Here</a>");
}
function onEachFeature_pop(feature, layer){
var pop = feature.properties.population;
var str = pop.toString();
layer.bindPopup("Population: " + str);
// if (med_age > 0){
// layer.setStyle({fillOpacity:0.7});
// }
// else{
// layer.setStyle({fillOpacity:0});
// }
// [0,15,25,35,45,55,65,75,85])
//[0,11,51,101,251,501,901,1201,1500])
if (pop > 1500){layer.setStyle({fillColor:"#03f",fillOpacity:0.9});}
else if (pop > 1201) {layer.setStyle({fillColor:"#08306B",fillOpacity:0.5});}
else if (pop > 901) {layer.setStyle({fillColor:"#08519C",fillOpacity:0.5});}
else if (pop > 501) {layer.setStyle({fillColor:"#2171B5",fillOpacity:0.5});}
else if (pop > 251) {layer.setStyle({fillColor:"#4292C6",fillOpacity:0.5});}
else if (pop > 101) {layer.setStyle({fillColor:"#6BAED6",fillOpacity:0.5});}
else if (pop > 51) {layer.setStyle({fillColor:"#9ECAE1",fillOpacity:0.5});}
else if (pop > 11) {layer.setStyle({fillColor:"#C6DBEf",fillOpacity:0.5});}
else if (pop > 0) {layer.setStyle({fillColor:"#DEEBF7",fillOpacity:0.5});}
else {layer.setStyle({fillColor:"#f7fbff", fillOpacity:0});}
layer.on("mouseover", function (e) {
//var txt = layer.bindPopup(feature.properties.median_age);
// var text = layer.bindPopup(str);
var box = document.getElementById('detail');
//layer.bindPopup(feature.properties.median_age);
box.innerHTML = "Population: " + str;
});
layer.on("mouseout", function (e) {
box = document.getElementById('detail');
box.innerHTML="";
});
}
$.getJSON("./flare5.json", function(json){
var geojson_d3 = L.geoJson(json,{
weight:0,onEachFeature:onEachFeature
})
var geojson3_d3 = L.geoJson(json,{
weight:0, onEachFeature:onEachFeature_pop
})
var overlays = {"median_age" : geojson_d3, "population":geojson3_d3};
$.getJSON("./flare4.json", function(data){
var geojson2_d3 = L.geoJson(data,{fill:true, weight:1.5, color:'#800026', fillOpacity: 0, onEachFeature:onEachFeature_zone}) //function(feature,layer) {layer.bindPopup(feature.properties.zoning)}})
overlays["zoning"] = geojson2_d3;
$.getJSON("./flare7.json", function(active){
var geojson2_d4 = L.geoJson(active,{fill:true, weight:1.5, color:'#800026', fillOpacity: 0, onEachFeature:onEachFeature_active}) //function(feature,layer) {layer.bindPopup(feature.properties.zoning)}})
overlays["active zoning"] = geojson2_d4;
var control = L.control.layers(baselayers, overlays).addTo(map)}
);
}
);
}
);
</script>
</body>
</html>
I am answering my own question. A friend suggest that I look again at the data retrieval. I ran snippets of the json code through jsonlint.com and noticed that the json files did not validate because I had terminated each of them with a semicolon. Apparently Safari will parse json files just fine this way, but other browsers will not. Once I deleted the semicolon, the files worked fine in IE and Firefox. I have not tested it yet in Chrome, but I suspect it will work now.
Thanks all for the suggestions.

CSS body class jquery switcher with cookies

I am using a background switcher so far compiled from a few examples and tutorials I have found around, it consists of a stylesheet and a few child classes that each contain a different background image; when the switcher image is clicked, the javascript sequentially toggles the next body class in order and writes a new value to the cookie. Everything works okay except for the cookie loading upon page load. If I refresh the page, the cookie does not recall, and thus the body class does not default to the last selected class. Here is the code
Here is a jsfiddle of it: http://jsfiddle.net/Lse3V/2/
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"><head>
<meta http-equiv="content-type" content="text/html;charset=ISO-8859-1" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="description" content="background switcha" />
<meta name="keywords" content="" />
<title>background switcha</title>
<link rel="stylesheet" href="style.css" type="text/css" media="screen" />
<script type="text/javascript" src="head.js"></script>
<script type="text/javascript">head.js( "jquery.js","back.js", function() { });</script>
</head>
<body class="orig">
</body>
</html>
style.css
body.green{background: #3F0 url(background1.jpg) center top fixed repeat}
body.blue{background: #00F url(background2.jpg) center -80px fixed repeat}
body.red{background: #F00 url(background3.jpg) center top fixed repeat}
body.grey,html{background: #666 url(background4.jpg) repeat}
body{min-height:800px}
#backgroundswap{display:block;display:inline-block;zoom:1;width:101px;height:22px;background-image:url(backgroundswap.png);background-repeat:no-repeat;margin-bottom:12px;}
body.green #backgroundswap{background-position:center bottom}
body.blue #backgroundswap{background-position:0 -66px}
body.red #backgroundswap{background-position:0 -44px}
body.grey #backgroundswap{background-position:0 -22px}
body.orig{background-position:0 0}
body.orig{
background: #FF0 url(background5.jpg) center top fixed repeat
}
back.js
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
options = options || {};
if (value === null) {
value = '';
options.expires = -1;
}
var expires = '';
if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
var date;
if (typeof options.expires == 'number') {
date = new Date();
date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
} else {
date = options.expires;
}
expires = '; expires=' + date.toUTCString();
}
var path = options.path ? '; path=' + (options.path) : '';
var domain = options.domain ? '; domain=' + (options.domain) : '';
var secure = options.secure ? '; secure' : '';
document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
} else {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
};
$(document).ready(function(){
//Switch backgrounds and create the cookie...
$("#backgroundswap").click(function(){
var old_bg = ["green","blue","red","grey","orig"];
var new_bg = ["blue","red","grey","orig","green"];
var currentClass = $('body').attr("class");
if(!Array.indexOf){ Array.prototype.indexOf = function(obj){ for(var i=0; i<this.length; i++){ if(this[i]===obj){ return i; } } return -1; } }
$('body').removeClass().addClass(new_bg[old_bg.indexOf(currentClass)]);
$.cookie('backswap', old_bg.indexOf($('body').attr("class")), { path: '/', expires: 365 });
});
});
head.js
(function(a){var b=a.documentElement,c=navigator.userAgent.toLowerCase().indexOf("msie")!=-1,d=false,e=[],f={},g={},h=a.createElement("script").async===true||"MozAppearance"in a.documentElement.style||window.opera;var i=window.head_conf&&head_conf.head||"head",j=window[i]=window[i]||function(){j.ready.apply(null,arguments)};var k=0,l=1,m=2,n=3;h?j.js=function(){var a=arguments,b=a[a.length-1],c=[];r(b)||(b=null),q(a,function(d,e){d!=b&&(d=p(d),c.push(d),v(d,b&&e==a.length-2?function(){s(c)&&b()}:null))});return j}:j.js=function(){var a=arguments,b=[].slice.call(a,1),c=b[0];if(!d){e.push(function(){j.js.apply(null,a)});return j}c?(q(b,function(a){r(a)||u(p(a))}),v(p(a[0]),r(c)?c:function(){j.js.apply(null,b)})):v(p(a[0]));return j},j.ready=function(a,b){r(a)&&(b=a,a="ALL");var c=g[a];if(c&&c.state==n||a=="ALL"&&s()){b();return j}var d=f[a];d?d.push(b):d=f[a]=[b];return j};function o(a){var b=a.split("/"),c=b[b.length-1],d=c.indexOf("?");return d!=-1?c.substring(0,d):c}function p(a){var b;if(typeof a=="object")for(var c in a)a[c]&&(b={name:c,url:a[c]});else b={name:o(a),url:a};var d=g[b.name];if(d)return d;for(var e in g)if(g[e].url==b.url)return g[e];g[b.name]=b;return b}function q(a,b){if(a){typeof a=="object"&&(a=[].slice.call(a));for(var c=0;c<a.length;c++)b.call(a,a[c],c)}}function r(a){return Object.prototype.toString.call(a)=="[object Function]"}function s(a){a=a||g;for(var b in a)if(a[b].state!=n)return false;return true}function t(a){a.state=k,q(a.onpreload,function(a){a.call()})}function u(a,b){a.state||(a.state=l,a.onpreload=[],w({src:a.url,type:"cache"},function(){t(a)}))}function v(a,b){if(a.state==n&&b)return b();if(a.state==m)return j.ready(a.name,b);if(a.state==l)return a.onpreload.push(function(){v(a,b)});a.state=m,w(a.url,function(){a.state=n,b&&b(),q(f[a.name],function(a){a()}),s()&&q(f.ALL,function(a){a.done||a(),a.done=true})})}function w(c,d){var e=a.createElement("script");e.type="text/"+(c.type||"javascript"),e.src=c.src||c,e.async=false,e.onreadystatechange=e.onload=function(){var a=e.readyState;!d.done&&(!a||/loaded|complete/.test(a))&&(d(),d.done=true)},b.appendChild(e)}setTimeout(function(){d=true,q(e,function(a){a()})},300),!a.readyState&&a.addEventListener&&(a.readyState="loading",a.addEventListener("DOMContentLoaded",handler=function(){a.removeEventListener("DOMContentLoaded",handler,false),a.readyState="complete"},false))})(document)
You are setting the cookie great, but there's nothing to check whether it's set or act on it if it does detect it. This bit of code will do just that for ya.
if($.cookie('backswap')) {
$('body').removeClass().addClass(old_bg[$.cookie('backswap')]);
};
There's some other minor adjustments to ensure the arrays are scoped for everything, so here's the entire chunk of code that's affected.
$(document).ready(function(){
window.new_bg = ["blue","red","grey","orig","green"];
window.old_bg = ["green","blue","red","grey","orig"];
if($.cookie('backswap')) {
$('body').removeClass().addClass(old_bg[$.cookie('backswap')]);
};
//Switch backgrounds and create the cookie...
$("#backgroundswap").click(function(){
currentClass = $('body').attr("class");
$('body').removeClass().addClass(new_bg[old_bg.indexOf(currentClass)]);
$.cookie('backswap', old_bg.indexOf($('body').attr("class")), { path: '/', expires: 365 });
});
});
Hope this helps!

Categories