Author - Web Developer - Educator
Found 4 results for tag "javascript"
RSS Feed

HTML API: Intro to Web Notifications API

After taking some time to get back into my craft, I realized that I had missed a lot of advancements in the HTML world, especially the evolution of the HTML API. Yes, there actually is an HTML API.

While researching some of the "new" API, I came across a bunch of articles by Aurelio De Rosa via SitePoint (a lot of good stuff there), and one of the items that caught my attention was the "Web Notifications API." Now, I will say that this stuff is still experimental (see the W3C's Working Draft for Notifications, so it's not widely supported and may even disappear. But for now, it's pretty awesome!)

Anyway, I'm sure you're not here to hear read about my day, so let's get to the point of the matter: HTML API - specifically, the Web Notifications API.

I know a lot of you just want to get to the demo and play with it, so here's a Working Demo (Chrome, Firefox, and Safari 7+ only)


What are "Web Notifications"?


If you use an email system like Gmail or Outlook, chances are you've already seen something like this:
Web Notification in the wild!

Well, those are technically desktop notifications and are usually controlled by software, not browsers. (Prior to HTML5, in order to get Desktop Notifications for Gmail, you had to download the "Gmail Notifier" application, and Outlook is already a software program to begin with).

The main difference is that these notifications (like the one above) are controlled by the browser - yes, the browser can control (certain) desktop notifications, and it's actually quite simple.

How to Use It


In an HTML file, add this bit of Javascript:
var notification = new Notification("New Email Received", { icon: "mail.png" })
That's pretty much it. No external libraries to load, no frameworks to bend around your whim - it's automatically built in to most modern browsers. Now, I know what you're asking: "What? That seems too simple! There has to be more." Don't worry, that was just the extremely core concept (provided by W3C). Technically, there is one more step to do: your application must first ask for permission before doing anything with the visitor's computer. (Yes, I know this seems a bit backwards, but for privacy, I can understand - especially with all of the ActiveX IE vaulnerabilities out there). This seems that the W3C wants to get rid of, but for now, it stays. (W3C says: Warning: In designing the platform notifications are the one instance thus far where asking the user upfront makes sense. Specifications for other APIs should not use this pattern and instead employ one of the many more suitable alternatives. [ref])
Notification.requestPermission(function(){
 
    //we're declaring a new object here
 
    var notification = new Notification(title, options);
 
});
There are 3 states to the "Permission" request: default (equivilant to "denied", because a choice has not been made yet), denied (the user denied the access, and therefore the request cannot proceed), or granted (the green light). This is similiar to when a browser (and/or application) asks to automatically use your physical location to determine items near you, like so:

Geolocation API in use

If you haven't already allowed a site to display desktop notifications (or allowed for geolocation, as the above image), then it will ask you for permission before proceeding:

Asking Permission

Overall, in accordance with "best practices", here's what I have learned/uncovered/researched:

First, you need to check to see if the API is supported. As this is still in the works, it isn't fully supported everywhere (for example, only Chrome, Firefox, and Safari 7+ support this - see http://caniuse.com/#feat=notifications for the full supported range).

In order to detect if the API is supported, add this bit of JS before you go calling Notifications.
//check to see if the API is supported
 
if (!('Notification' in window)){
 
    //API not supported. Show a message or something
 
    ....
 
} else {
 
    // API is supported. Do things
 
    ....
 
}
Therefore, if you have any buttons, links, or other items that make the notifications appear based on calling them, then you can disable them safely (or, if you are basing it off of automatic notifications, like emails, scores, or calendars, you can safety defer the notifications instead of having an error thrown).

Let's get fancy


The above sample is pretty much all you need to know for calling Notifications. If you want to get a little fancy with things, try this:
title = 'Email Received';
 
options = {
 
    body: 'You have a total of 3 unread emails',
 
    tag: 'preset', //The UID of the notification
 
    icon: 'https://mail.google.com/mail/u/0/images/favicon2.ico'
 
};
Before we go into detail about this, let's break it down:

  • title: This is the title of the Notification (duh)

  • options: This outlines a few of the Instance options available in the API
    (technically, everything is optional)

    • dir: This determines the text direction that the notification will be displayed (options are auto, ltr (left to right), or rtl (right to left) (default: auto)

    • lang: The language that the notification should be displayed in (example: 'en' for 'english') - (default: default language for computer)

    • body: The message that is displayed in the notification, like the body of a letter (default: blank)

    • tag: I like to think of this as the UID (Unique IDentifier) of the notification. Examples in the W3C Draft Documentation show usage of multiple instances of notification windows, so if you want one for your Email, Calendar, Reminders, etc, you can name each appropriately instead of just having to fall back on just 1. (default: blank)

    • icon: If you have a jpg, png, ico, or any other image file to show with the notification, you can list it here (I'd recommend the full absolute path of a web file instead of locally) (default: blank)

Those are all of the options available for the Notification API right now. Maybe more will come in the future - it just depends on what the official word is on the development.

FAQ


Can the notification automatically close after a few seconds?

I'd like to say 'yes', but the answer is unfortunately, no - at least, not completely.

I've tested my demo in Chrome and Firefox and had different results. I set up a setTimeout right after the notification is shown and tested it.
notification.onshow = function() { setTimeout(notification.close, 15000) }
However, Firefox displays the notification and automatically dismisses it after 5 seconds, regardless of the timeout, and Chrome will display the notification until you close it. Apparently, the problem is that the drafted Event Handlers don't register in the browsers, yet. I've tried to implement a calling feature of event.type == 'onshow', then call the setTimeout function, but to no avail. I've also tried to match up the event.type prior to the forEach function, but yet again, nothing.

Demo

In case you missed it above, here's the live demo again. It provides a call button that calls the notification on demand. I'm sure you can play around with it and figure out how it works.

References

Mozilla Dev Documentation: https://developer.mozilla.org/en-US/docs/Web/API/Notification W3C Draft: w3.org/TR/notifications/ Articles by Aurelio De Rosa: sitepoint.com/author/aderosa/ Aurelio's Notifications API Demo: http://aurelio.audero.it/demo/web-notifications-api-demo.html "Can I Use" browser feature comparison: http://caniuse.com/#feat=notifications


Tags:#html #api #javascript #w3c #mozilla #demos #tutorials

RSS Feed

HTML5 Canvas - Bouncing Ball Example

At this point, I'm trying to stay up with HTML5 programming, and I feel like I'm a little behind the times.

So, because I'm in a Python class (via Coursera by Rice University) learning about interactive programming (more specifically, "Pong" was this week's project) and seeing Google's anniversary edition of Breakout, I felt inspired to learn how innovative HTML5 could be, so I looked up some HTML5 references and thought I'd try my hand at it.

Well, I combined by Python experiences and some HTML5 canvas examples and created some ball-bouncing joy. Want a demo? Here's a demo!

Here's a screenshot of it:
Bouncing Ball
I've taken out the clear() function to show it in motion


Even though this is very simple (as compared to some more advanced HTML5 stuff), I thought I'd go ahead and put this here for others to view/use/learn from.

Here's the HTML:
 
<!DOCTYPE html>
 
<html>
 
	<head>
 
		<meta charset='utf-8'/>
 
		<title>Ball Canvas Test</title>
 
		<link href='main.css' rel='stylesheet'/>
 
		<!--[if lt IE 9]>
 
			<script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
 
		<![endif]-->
 
		<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js'></script>
 
		<script src='main.js'></script>
 
	</head>
 

 
	<body>
 
		<div id='debug'></div>
 
		<div id='container'>
 
			<canvas id='scene'></canvas>
 
		</div>
 

 
		<footer>
 
			© 2013 - Kyle Perkins
 
		</footer>
 
	</body>
 
</html>
 


Here's the CSS: (this uses a standard Reset CSS, started by Eric Meyers)
 
@import url("//dev.shadowdev.com/reset.css");
 
html, body{
 
	display: block;
 
	text-align: center;
 
}
 
#debug{
 
	position: absolute;
 
	top: 50px;
 
	right: 50px;
 
}
 
canvas{
 
	margin: auto;
 
	display: block;
 
	border: 5px #000 solid;
 
	background-color: #efefef;
 
}
 


And here's the fancy-smancy Javascript:
var canvas, ctx;
 
var circles = [];
 
var circleCount = 4; 
 
var velocity_set = 2;
 

 
function oneorzero(num){
 
	// simple function to randomly get 0 or 1
 
	if (Math.round(Math.random())==1) num *= -1;
 
	return num;}
 

 
function Circle(x,y,radius, color){
 
	// get the information stored for eac ball
 
	this.x = x;
 
	this.y = y;
 
	this.radius = radius;
 
	this.color = color;
 
	var V1 = oneorzero(velocity_set);
 
	var V2 = oneorzero(velocity_set);
 
	// velocity is set as an array so we can have the [x,y] values
 
	// [5,5] means ^,>
 
	// [-5, -5] means V,<
 
	this.velocity = new Array(V1, V2);
 
}
 

 
function clear(){
 
	// clear the screen (prevent "dirty canvas")
 
	ctx.clearRect(0,0, ctx.canvas.width, ctx.canvas.height);
 
}
 

 
function getrand(){
 
	// function to randomly get a value between 0-255 (one value for R, G, and B each)
 
	return Math.floor((Math.random()*255)+1);
 
}
 

 
function drawCircle(ctx, x, y, radius, color) { // draw circle function
 
//	$('#debug').html("X:"+x+" Y:"+y);
 
//    ctx.fillStyle = 'rgba('+r+', '+g+', '+b+', 1.0)';
 
	ctx.beginPath();
 
	ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
 
	ctx.fillStyle = "rgb("+color+")";
 
	ctx.fill();
 
	ctx.stroke();
 
//    ctx.closePath();
 
}
 

 
function drawScene(){ //main draw function
 
	clear(); //clear the canvas
 
	// this is only for additional draw functionality (testing only)
 
/*	ctx.beginPath();
 
      ctx.arc(canvas.width/2, canvas.height/2, 70, 0, 2 * Math.PI, false);
 
      ctx.fillStyle = 'blue';
 
      ctx.fill();
 
      ctx.lineWidth = 5;
 
      ctx.strokeStyle = '#fc0';
 
      ctx.stroke();
 
*/
 
	
 
	var ball_info ="";
 
	for (var i=0; i 0)
 
		$('#debug').html(ball_info);
 
}
 

 
////////////////////////////////////////
 

 
$(function(){
 
	// call these setup properties upon load
 
	canvas = document.getElementById("scene");
 
	ctx = canvas.getContext('2d');
 

 
	// this is to make sure the canvas spreads across the screen
 
	ctx.canvas.width = window.innerWidth-10; // the canvas has a 5px border
 
	ctx.canvas.height = window.innerHeight-50; // 50 is only for the footer info
 

 
	var circleRadius = 25;
 
	var width = canvas.width;
 
	var height = canvas.height;
 

 
	for (var i = 0; i < circleCount; i++){
 
		// start at random position
 
		var x = Math.random()*(width*.9);
 
		var y = Math.random()*(height*.9);
 
		var r = getrand();
 
		var g = getrand();
 
		var b = getrand();
 
		ballColor = r+","+g+","+b;
 
		// add circle to array
 
		circles.push(new Circle(x,y,circleRadius, ballColor));
 
	}
 
	setInterval(drawScene, 1); // loop drawScene - aka: "draw handler"
 
});
 

 
function animate(ball, canvas, context) {
 
	// this is for adding (aka: "move") the ball based on the velocity increase/decrease
 
	// velocity is an array
 
        ball.x += ball.velocity[0];
 
	ball.y += ball.velocity[1];
 
	
 
        if( (ball.x > (canvas.width - ball.radius)) || (ball.x < (0 + ball.radius))) {
 
		// bounce off left or right wall
 
		ball.velocity[0] *= -1;
 
        }
 
	if ( (ball.y > (canvas.height - ball.radius)) || (ball.y < (0 + ball.radius))){
 
		// bounce off top or bottom wall
 
		ball.velocity[1] *= -1;
 
	}
 

 
	// draw the circles with on the (canvas, x position, y position, radius, color)
 
        drawCircle(ctx, ball.x, ball.y, ball.radius, ball.color);
 
      }


I hope this works for some people learning how to use HTML5 and the "velocity effect"


Tags:#html5 #css #javascript #python #tutorials

RSS Feed

Bachelor for a Week 2013: Day 2

I did not report in yesterday because I was in immense pain, almost flu-like symptoms. Needless to say, I spent most of the day in bed, surrounded by cats.

Today, however, was much better. For me, but not for the weather.
Garfield

(Seriously: a major downpour of rain today, snow last Thursday, great short-sleeve weather on previous weekends, then heavy gusts throughout the month....all that we're missing is hail)

I moved the Wii into the guest room/office so I could have some entertainment while I coded away. Let's just say that if I had a fridge and a toilet in this room, I'd never leave.

I watched a good chunk of Enterprise today. Now, I'm only 6 episodes away from the end. What's on my "To Watch" list next?

I also wrote 3 articles for Shadow Dev, which will be premiering over the course of the following week.

I worked on the small blurbs and larger fancyboxes of our new pricing page, which should also be premiering sometime soon.

I lastly worked on the Portal 2.0. I made some great stride with window.location.hash when trying to reload pages based on post-hash URI's. jQuery just became a lot better now.

Here's what I am happy about today:
 
$(function(){
 
	$('#db_menu').find('a').live('click', function(){
 
		var link_id = $(this).attr('id');
 
		$.ajax({
 
			type: "GET",
 
			url: "/get_box.php",
 
			data: { q: link_id },
 
			success: function(data){
 
				$('#db_box').html(data);
 
			}
 
		});
 
	});
 

 
	var path = window.location.hash;
 
	if (path==""){
 
		$('#main').click();
 
		window.location.hash = "#main";
 
	}
 
	else
 
		$(path).click();
 
});
 


I basically had to scrap the whole project and start from almost square 1. I kept the original login scripts along with the database structures in tact. My main starting point was from the Dashboard and so on.

My plan over the following week is to improve the new Portal to a point that it is ready to launch. The plan to launch Portal 1.0 with the new site launch had a small...drawback. It didn't convert with the new CSS well, and had a few delayed bugs in it, along with a good chunk missing for the Clients. My goal is for Portal 2.0 to fix that.

I don't usually like scrapping projects during development, but the pro is that the revamp comes out much cleaner than originally expected. Only time (and late nights) will tell if my feats become useful.

On a some-what related note, I was told by Keat (I don't recall if it was today or yesterday, as both days are a bit of a blur) that it is 4° out in Frisco right now. I would have been okay (that's a joke) with 4° Celsius, but we're in America, and that's 4° Fahrenheit. I do wish her the best in that frigid temperature. I'll stick with the rainy 40° here.

XKCD


Also, I used a gift code from StateFarm to order the next Star Trek/Doctor Who Crossover Vol. 2 comic book today. It only cost me $5.71 (and that was with shipping and tax). It would have cost me somewhere around $18 in a shop. Although I do support local shops, I had a gift code that I had to use or it would have expired.


Tags:#jquery #javascript #enterprise #startrek #projects #garfield #keat #articles #xkcd #doctorwho #comics

RSS Feed

A Brief History of Programming

Saw this via @GeeksAreSexy - it's amazing how the Java vs PHP and Ruby duels have progress

History of Programming


Tags:#programming #java #php #ruby #javascript #fortran #cobol #basic #c #pascal #c++ #python #perl #ruby #rails