Skip to content

Instantly share code, notes, and snippets.

View Chalarangelo's full-sized avatar
💻
Coding...

Angelos Chalaris Chalarangelo

💻
Coding...
View GitHub Profile
// Get page scroll percentage.
function getScrollPercent() {
return (
(document.documentElement.scrollTop || document.body.scrollTop)
/ ( (document.documentElement.scrollHeight || document.body.scrollHeight)
- document.documentElement.clientHeight)
* 100);
}
function someFunction(){
if (true){
// This variable is defined inside these
// curly braces, which means its part of the
// scope of this block and cannot be accessed
// by other parts of someFunction.
let blockVariable = 30;
// However, using the 'var' keyword this variable,
// while defined inside the same block, is part of
if ('serviceWorker' in navigator) {
navigator.serviceWorker
.register('./service-worker.js')
.then(function() { console.log('Registered service worker!'); });
}
// This is a function and it defines its own
// local scope. argumentVariable is part of the
// function's scope, as it is an argument in its
// definition.
function parentFunction(argumentVariable){
// functionVariable and anotherVariable are both
// part of parentFunction's local scope.
var functionVariable = 10;
let anotherVariable = 15;
function user(username, password){
// Here we use closures to define public functions
// that can access private variables.
return {
getUsername() { return username; },
setUsername(newUsername) {username = newUsername; },
checkPassword(givenPassword) { return password == givenPassword; }
}
}
var cacheName = 'mockApp-v1.0.0';
var filesToCache = [
'./',
'./index.html',
'./manifest.json',
'./static/js/bundle.js'
];
self.addEventListener('install', function(e) {
e.waitUntil(caches.open(cacheName)
// Create a function.
function f(x){
return x * x;
}
// Use the function.
f(5); // 25
// Create an anonymous function and assign
// it to a variable.
var g = function(x){
// This variable is part of the global scope
var globalVariable = 10;
function someFunction(){
// globalVariable is accessible from someFunction,
// as it is part of the global scope
console.log(globalVariable);
}
someFunction(); // Prints 10
self.addEventListener('activate', function(e) {
e.waitUntil(caches.keys()
.then(function(keyList) {
return Promise.all(keyList.map(function(key) {
if (key !== cacheName)
return caches.delete(key);
}));
}));
return self.clients.claim();
});
@Chalarangelo
Chalarangelo / http-get-async.js
Created July 15, 2017 21:45
AJAX GET request function
// Send a 'GET' request to the specified url and run the callback function when it completes.
function httpGetAsync(url, callback) {
var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4 && xmlHttp.status == 200)
callback(xmlHttp.responseText);
};
xmlHttp.open('GET', url, true);
xmlHttp.send(null);
}