Introduction to JSON

JSON (JavaScript Object Notation) is a format to represent data, even though it has JavaScript in its name, it is language independent. 

JSON is simply a collection of name/value pairs, In this blog post, we will focus on JSON in JavaScript.

Continue reading Introduction to JSON

Introduction to Express JS

Express.Js is a popular node js framework which makes developing API’s a breeze.

Continue reading Introduction to Express JS

Promise – finally

The finally method of a Promise  allows you to execute code after a promise has been settled. If the promise succeeds or fails the finally method is called. This is useful if you want to run some code regardless of the outcome of the promise. The promise finally method is similar to the finally method in a try catch finally block.

Continue reading Promise – finally

Introduction to CSS Variables

CSS Variables lets you use variables in your CSS rules, which results in less repetition, more flexibility and easier theming of your site. Unlike SASS and LESS, CSS Variables are part of the DOM, so you can use them directly in the browser.

Recent versions of most browsers support CSS Variables, IE does not support it, you can find the list of browsers supporting it here. There is a ploy-fill available here.

Read more

Introduction to Django

Django is a python framework that lets you quickly and easily build secure data driven websites.

Django uses the Model-View-Template (MVT) architecture, which has three components:

  • Models are used for managing the data.
  • View handle the application logic , they fetch data from the models and display the results in the templates.
  • Template handles the presentation of data in a particular format as specified by the View.
Installation

Installing django is easy using pip which is a package management solution.

You will need python installed on your system, To install Django, we recommend that your first create a virtual environment and then run the command

pip install django

Django is now installed, now you need to create an project, you can create an project using the following command

django-admin.py startproject PROJECT_NAME

Which will create a  folder named PROJECT_NAME with files inside it belonging to your project, now you need to create an app, a Django project can use one or more apps. Create the app by first changing directory into the newly created project directory, then run the following command

python manage.py startapp app_name
Web App

We need to connect our app to the project, we do this by modifying the settings.py file present in the Project folder

In the settings.py file add your app name to the INSTALLED_APPS list

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app_name'
]

next inside the apps folder, create a folder called “templates”, this will be where you store your app template files.

Next we need to connect the urls of the app to the project urls, to do this open the urls.py file in the app directory and add the following contents

from django.conf.urls import url
from . import views

urlpatterns = [     
url(r'^$', views.home, name='home'),
]

the urlpatterns is a list of urls, each url consists of 3 parts

r’^$’ is the regular expression used to call the view function when the url matches the given regular expression

views.home is the views function that will be called for this url

name=’home’  you can also optionally provide a name for your url

Next in the urls.py file in the project directory add the following import statement

from django.conf.urls import include

Next add the following url to the urlpatterns list

url(r'', include('app.urls')),

The above code matches the url with the regular expression, if it matches, the includes function is used to include the app urls.py file to handle the request.

Next we need to add some logic to the code, for this we add code in the views.py file. This is where the logic of the app resides.

def home(request):
return render(request, 'home.html', {})

In the above block of code we create a function called home, which takes in the request object, it then returns the home.html page 

Next create a directory called templates inside the app directory and place a html file called “home.html” inside it, write any html content within the file.

Now in the terminal or command prompt run the command

python manage.py runserver

The above command will start a webserver and if you open the url localhost:8000 in a browser , Django will get the url, see that it matches the “home” url pattern, it will then call the home view function, the function will then return the home.html file to the browser which you can view.

Django can do a lot more than what is mentioned in this post, If you would like to learn more about Django, then the official documentation is a good place to start.

Infinite scrolling using Intersection Observer

In a previous blog post, we introduced the Intersection Observer API , which is used to asynchronously tell us when an element intersects with another.

 In this post, we will show just how easy it is to add infinite scrolling to dynamically load more content to when the user scrolls to the bottom of the page. The code for this demo is available here

HTML

For the HTML, we need a container to add elements to and we need an element to tell us when the user has reached the bottom of the page.

div id="infinite-container">
</div>

<div id="infinite-indicator">
  <h2 class="text-center">Loading More ...</h2>
</div>

In the above code, we have a div with id “infinite-container” which will hold all the content and an div with id “infinite-indicator”  which when visible means that the user has scrolled to the bottom of the page.

Javascript

First, we create an instance of the intersection observer

// create an intersection observer, it calls the loadMore function when the intersection of the element changes
const observer = new IntersectionObserver(loadMore);

Next we create references to the div elements

// element to detect end of page
var indicator = document.querySelector('#infinite-indicator');

// element which contains the images
var container = document.getElementById('infinite-container');

Next we start observing

observer.observe(indicator);

We also have an array of images which will be loaded by the loadMore function

// array of images
var img_arr = [
'images/ishan-seefromthesky-1113275-unsplash.jpg',
'images/eberhard-grossgasteiger-1254739-unsplash.jpg',
'images/paula-russell-1253027-unsplash.jpg',
'images/artem-sapegin-1252570-unsplash.jpg',
'images/sylas-boesten-1253896-unsplash.jpg',
'images/will-turner-1254397-unsplash.jpg'
]

Next we have to implement the loadMore function which is called when the infinite-indicator div is visible.

function loadMore(arr) {
  // if the element is intersectingif(arr[0].isIntersecting){
  // get a random index from the array
  var random = Math.floor(Math.random()*6);

  // create an image and append it to the container and set the source of the image
  var img = document.createElement('img');
  container.append(img);
  img.src = img_arr[random];
  }
}

In the above code, we first check if the element isIntersecting, which means that its visible, if it is ,we then get a random index, create a new image and add it to the container.

Async Await

Previously we had a small introduction on Promises which are used in asynchronous events and getting data after an event occurs, Async Await is a JavaScript API that allows you to write asynchronous code in a synchronous manner so that your code is easier to read and debug.  

Async Await is just different syntax for using Promises, they use promises in the background. Most browsers support Async Await, you can get the full list here.

Continue reading Async Await

Page Visibility API

The Page Visibility API tells you if the current page is visible or not and also informs you when the page becomes hidden or visible. 

This API is supported in almost all browsers, you can find the full list here.

Uses

Before we go into the details of the API, it is helpful to know why its useful to us.

When a page is in the background, you can do the following things

  • pause videos and animations so since the user is not looking at it anyway
  • Slow down or stop updates from your server thereby saving user bandwidth and lessening load on your servers.
  • Notify the user of events via notifications so that they can get back to your website.
  • Monitor how long users actually spend on your website and pages.

API Methods

document.hidden

document.hidden returns true if the entire page is currently hidden.

document.visibilityState

It has four possible values which specify finer level of detail about the visibility of the page.

a) Visible – Document is completely visible

b) hidden – Document is completely visible

c) Document is loaded but is offscreen

d) unloaded – the document is not loaded

visibilitychange

This is an event that you can listen to which gets triggered when the visibility of the page changes

Example:

document.addEventListener("visibilitychange", function(){
if(document.hidden == true){
console.log('the page is now completely hidden');
}else{
console.log('the page is now visible');
}
});

Picture-in-Picture (PiP) API

One of the newer browser features is the Picture-in-Picture API which allows you to play your video in a small re-sizable, movable overlay video element so that you can continue to watch your video even after you change tabs or minimize the tab containing the video.

Continue reading Picture-in-Picture (PiP) API

Introduction to HTML LocalStorage API

Web apps can store data locally within the user’s browser instead of storing data in cookies.  LocalStorage is per origin so all pages from an origin can store and access the same data.

Continue reading Introduction to HTML LocalStorage API