Design Timeline using CSS and Jquery

Timeline design is the current web trend that visualizes the data in an interesting way. Today I want to discuss about how to design a timeline in a simple way with JSON data feed , that using CSS pseudo elements such as:before and :after. Pseudo elements are used to apply special effects to selectors. This post is a combination of my previous post, please take a quick look at this demo and try demo script with your WAMP server.

csstimeline PHP and ASP

The ::before selector inserts content before the content of the selected element(s).

CSS Code

#updates
{
position:relative;
padding:20px 0px 20px 0px;
}
#updates:before
{
content: ”;
position: absolute;
top: 0px;
bottom: 0px;
width: 5px;
background: #999999 ;
}
.timeline_square
{
width:12px;
height:12px;
display:block;
position: absolute;
left:-4px;
border-top:3px solid #e8eaed;
border-bottom:3px solid #e8eaed;
margin-top:-8px;
}

Status Update HTML Code
Check my previous postStatus Message Design with CSS
<div class=”stbody”>
<span class=”timeline_square color1″></span>
<div class=”stimg”><img src=”profile.jpg” /></div>
<div class=”sttext”>
<span class=”stdelete” title=”Delete”>X</span>
<b>Srinivas Tamada</b><br/>
9lessons Programming Blog
<div class=”sttime”>10 seconds aga.</div>
<div class=”stexpand”>
//Youtube IFrame Code
</div>
</div></div>
users.json
This contains Users data feed, you can generate this using PHP code.
{
Messages“:[
{
“user”:”Srinivas”,
“message”:”9lessons Programming Blog http://www.9lessons.info . “,
“avatar”:”srinivas.jpg”,
“embed”:””,
“time”:”16 seconds ago”
},
{
“user”:”Arun”,
“message”:”Everything is possible. “,
“avatar”:”arun.jpg”,
“embed”:””,
“time”:”18 seconds ago”
},
{
“user”:”Joker”,
“message”:”If you are good at something, never do it for free”,
“avatar”:”joker.png”,
“embed”:”<iframe height=’315′ src=’//www.youtube.com/embed/FalHdi2DkEg’ width=’560′></iframe>”,
“time”:”28 seconds ago”
},
…………..
…………..
…………..
]
}
index.html
Contains Jquery and JavaScript code, here $.getJSON parse the JSON data object.
<script src=”js/jquery.min.js”></script>
<script src=”js/jquery.linkify.min.js”></script>
<script src=”js/jquery.livequery.js”></script>
<script>
$(document).ready(function()
{//Formatting the text that contains URLs (text to link)
$(“.sttext”).livequery(function ()
{
$(this).linkify({ target: “_blank”});
});

//Parsing JSON object.
$.getJSON(“users.json”, function(data)
{
var totalCount=5;
var jsondata=”;
$.each(data.Messages, function(i, M)
{
//Generating random numbers for different dot colors
var num = Math.ceil(Math.random() * totalCount );
jsondata +='<div class=”stbody”>’
+'<span class=”timeline_square color’+num+'”></span>’
+'<div class=”stimg”><img src=”‘+M.avatar+'” /></div>’
+'<div class=”sttext”><span class=”stdelete”>X</span>’
+'<b>’+M.user +'</b><br/>’
+M.message+'<div class=”sttime”>’+M.time
+'</div><div class=”stexpand”>’+M.embed+'</div></div></div>’;
});
$(jsondata).appendTo(“#updates”);
});

//Delete record
$(‘body’).on(“click”,”.stdelete”,function()
{
var A=$(this).parent().parent();
A.addClass(“effectHinge”);
A.delay(500).fadeOut(“slow”,function(){
$(this).remove();
});
});});
</script>
//HTML Code
<div id=”updates”></div>

Deleting record animation effect, please check my previous post CSS3 Animation Effects with Keyframes

CSS code
Random colors for timeline square points.

.color1
{
background-color:#f37160
}
.color2
{
background-color:#50b848
}
.color3
{
background-color:#f39c12
}
.color4
{
background-color:#0073b7
}
.color5
{
background-color:#00acd6
}
.effectHinge
{
animation:hinge 1s;
-webkit-animation:hinge 1s; /* Safari and Chrome */
}

 

custom Audio Player using Jquery and HTML5

Today I want to discuss how to publish a voice recording messages on newsfeed using Jquery and HTML5 with custom HTML5 audio player. Take a quick look at the live demo, make sure use the microphone for better result.

Database
Newsfeed table contains all the user update details.

CREATE TABLE newsfeed(
id INT PRIMARY KEY AUTO_INCREMENT,
userUpdate TEXT,
user_id_fk INT,
audioMessage TEXT,
status ENUM(‘0′,’1’) DEFAULT ‘1’);

JavaScript
You have to include all these JavaScript library files.

<script src=”recorderControl.js”></script>
<script src=”js/jquery.min.2.1.js”></script> //Jquery
<script src=”js/jquery.stopwatch.js”></script> //Jquery Stop Watch
<script src=”recorder.js”></script>
<script type=”text/javascript”>
$(document).ready(function(){

—–
—–
—–

});
</script>

Custom Audio Player HTML Code
HTML code for custom designed audio player, here the actual HTML5 player is in hidden mode. Number 10 refers to user’s session id.
<div class=”audioContainer”>
<div class=”audioProgress” id=”audioProgress10′” style=”width:0px”></div>
<div class=”audioControl audioPlay” rel=”play” id=”10“></div>
<div class=”audioTime” id=”audioTime10′”>00.00</div>
<div class=”audioBar”></div>
<audio preload=”auto” src=”data:audio/mp3;base64,//sUxAAABAArMFRhgA..” type=”audio/mpeg” class=”a” id=”audio10′”><source></audio>
</div>
Audio Player CSS
Focus on colored CSS properties.
audio{display:none}
.audioContainer
{
height:50px;width:250px;
border:solid 1px #dedede;
position:relative;
}
.audioProgress
{
height:50px;float:left;background-color:#f2f2f2;z-index:800
}
.audioControl
{
position: absolute;float:left;width:52px;height:48px;;
}
.audioTime
{
position: absolute;width: 45px;height: 20px;margin-left:199px;float:right;
}
.audioBar
{
height: 3px;
background-color: #cc0000;
position: absolute;width: 147px;margin-left: 53px;
}
.audioPlay
{
background:url(‘../images/play.png’) no-repeat
}
.audioPause
{
background:url(‘../images/pause.png’) no-repeat
}
Audio JavaScript
Contains JavaScript code $(‘body’).on(‘click’,’.audioControl’, function()audioControlis the CLASS name of the DIV tag. Using $(this).attr(“id”) calling the player ID.
// Utility method that will give audio formatted time
getAudioTimeByDec = function(cTime,duration)
{
var duration = parseInt(duration),
currentTime = parseInt(cTime),
left = duration – currentTime, second, minute;
second = (left % 60);
minute = Math.floor(left / 60) % 60;
second = second < 10 ? “0”+second : second;
minute = minute < 10 ? “0”+minute : minute;
return minute+”:”+second;
};

// Custom Audio Control using Jquery
$(“body”).on(“click”,”.audioControl”, function(e)
{
var ID=$(this).attr(“id”);
var progressArea = $(“#audioProgress”+ID);
var audioTimer = $(“#audioTime”+ID);
var audio = $(“#audio”+ID);
var audioCtrl = $(this);
e.preventDefault();
var R=$(this).attr(‘rel’);
if(R==’play’)
{
$(this).removeClass(‘audioPlay’).addClass(‘audioPause’).attr(“rel”,”pause”);
audio.trigger(‘play’);
}
else
{
$(this).removeClass(‘audioPause’).addClass(‘audioPlay’).attr(“rel”,”play”);
audio.trigger(‘pause’);
}// Audio Event listener, its listens audio time update events and updates Progress area and Timer area
audio.bind(“timeupdate”, function(e)
{
var audioDOM = audio.get(0);
audioTimer.text(getAudioTimeByDec(audioDOM.currentTime,audioDOM.duration));
var audioPos = (audioDOM.currentTime / audioDOM.duration) * 100;
progressArea.css(‘width’,audioPos+”%”);
if(audioPos==”100″)
{
$(“#”+ID).removeClass(‘audioPause’).addClass(‘audioPlay’).attr(“rel”,”play”);
audio.trigger(‘pause’);
}
});
// Custom Audio Control End
});

Controlling audio controls with Jquery trigger()

Record Button HTML Code
Contains simple HTML code.

<img src=”images/Microphone.png” id=”recordButton” class=”recordOff”>
<span id=”recordHelp”>Allow your microphone.</span>
<div id=”recordContainer” class=”startContainer”>
<div id=”recordTime”> <span id=”sw_m”>00</span>:<span id=”sw_s”>00</span></div>
<div id=”recordCircle” class=”startRecord”><div id=”recordText”>Record</div></div>
</div>
CSS
#recordCircle
{
margin: 0px auto;
font-weight: bold;
cursor: pointer;
width: 100px;
height: 100px;
text-align: center;
-moz-border-radius: 50px;
-webkit-border-radius: 50px;
border-radius: 50px;
}
Record Button JavaScript
This script calls record.js for recording the audio.
$(“body”).on(‘click’,’.recordOn’,function()
{
$(“#recordContainer”).toggle();
});
//Record Button
$(“#recordCircle”).mousedown(function()
{
$(this).removeClass(‘startRecord’).addClass(‘stopRecord’);
$(“#recordContainer”).removeClass(‘startContainer’).addClass(‘stopContainer’);
$(“#recordText”).html(“Stop”);
$.stopwatch.startTimer(‘sw’); // Stopwatch Start
startRecording(this); // Audio Recording Start
}).mouseup(function()
{
$.stopwatch.resetTimer(); // Stopwatch Reset
$(this).removeClass(‘stopRecord’).addClass(‘startRecord’);
$(“#recordContainer”).removeClass(‘stopContainer’).addClass(‘startContainer’);
$(“#recordText”).html(“Record”);
stopRecording(this); // Audio Recording Stop
});
record.js
Modified and included following code in record.js for storing the audio data in Base64 format.
function uploadAudioBase64(audiosrc)
{
var dataString =’audiosrc=’+audiosrc;
$.ajax({
type: “POST”,
url: “uploadAudio.php”,
data: dataString,
cache: false,
success: function(html)
{
var ID = Number(new Date()); //Timestamp
var A='<div class=”audioContainer”>’
+'<div class=”audioProgress” id=”audioProgress’+ID+'” style=”width:0px”></div>’
+'<div class=”audioControl audioPlay” rel=”play” id=”‘+ID+'”></div>’
+'<div class=”audioTime” id=”audioTime’+ID+'”>00.00</div>’
+'<div class=”audioBar”></div>’
+'<audio preload=”auto” src=”‘+audiosrc+'” type=”audio/mpeg” class=”a” id=”audio’+ID+'”><source></audio>’
+'</div>’;
var B='<div class=”stbody”><div class=”stimg “>’
+'<a href=”https://labs.9lessons.info/srinivas”><img src=”http://www.gravatar.com/avatar/c9e85bd3f889cc998dd1bb71d832634b?d=mm&s=230″ class=”big_face ” alt=”You” ></a></div>’
+'<div class=”sttext”><div class=”sttext_content”><span class=”sttext_span”><b><a href=”https://labs.9lessons.info/srinivas”>You</a></b> </span>’
+A
+'</div></div></div>’;
$(“.recordingslist”).prepend(B);
}
});
}
updateAudio.php
Inserting the audio Base64 data into newsfeed along with user session id.
<?php
include(‘db.php’);
$session_id=’1′;
if($_POST[‘audiosrc’] && !empty($session_id))
{
$audiosrc=$_POST[‘audiosrc’];
$query=mysqli_query($db,”INSERT INTO `newsfeed` (`user_id_fk`, `audioMessage`) VALUES ( ‘$session_id’, ‘$audiosrc’)”)or die(mysqli_error($db));
}
?>
This way data will store audio data into newsfeed table.
Audio Recording with Jquery and HTML5 PHP and ASP
db.php
Database connection you have to modify username, password and database values.
<?php
define(‘DB_SERVER’, ‘localhost’);
define(‘DB_USERNAME’, ‘username’);
define(‘DB_PASSWORD’, ‘password’);
define(‘DB_DATABASE’, ‘database’);
$db = mysqli_connect(DB_SERVER, DB_USERNAME, DB_PASSWORD,DB_DATABASE) or die(mysqli_connect_error());
$path = “uploads/”; //Images upload folder
?>

Vanilla JS Browser Default Javascript

vanilla PHP and ASP

vanilla PHP and ASP

Start Vanilla – The Document Ready Event
Code runs after the browser finishes loading the document, including images and banner ads.

document.addEventListener(‘DOMContentLoaded’, function()
{
//JavaScript methods go here.
});

Click Event
Contains plain JavaScript code, here linkID is the ID name of anchor tag. You can prevent the default behavior by calling e.preventDefault();

document.addEventListener(‘DOMContentLoaded’, function()
{
//Click Event Code
document.querySelector(“#linkID”).addEventListener(“click”, function(e)
{
alert(“Click event triggered”);
e.preventDefault();
});});//HTML Code
<a href=”#” id=”linkID”>Click Event</a>

Hide & Show Div
The divBlock slowly disappears when clicked hideLink.

document.querySelector(“#hideLink”).addEventListener(“click”, function()
{
document.getElementById(‘divBlock’).style.display = ‘none’
});document.querySelector(“#showLink”).addEventListener(“click”, function()
{
document.getElementById(‘divBlock’).style.display = ”
});//HTML Code
<a href=”#” id=”hideLink”>Hide</a> — <a href=”#” id=”showLink”>Show</a>
<div id=”divBlock”>

</div>

Add & Remove Class
Applying and Removing a HTML Class.

CSS Code
You have to include following CSS code within the tag HEAD of the document

.hidden{display:none}

You can use following code with in the function HTMLElement.classList, this allows to add or remove the class of an element.

document.getElementById(‘divBlock’).classList.add(‘hidden’);

document.getElementById(‘divBlock’).classList.remove(‘hidden’);

//HTML Code
<a href=”#” id=”hideLink”>Hide</a> — <a href=”#” id=”showLink”>Show</a>
<div id=”divBlock”>

</div>

Toggle Class
This method simply toggles the visibility of elements, here the code is adding and removing the class hidden.

document.querySelector(“#toggle”).addEventListener(“click”, function()
{
document.getElementById(‘divBlock’).classList.toggle(‘hidden’);
});
//HTML Code
<a href=”#” id=”hideLink”>Toggle</a>
<div id=”divBlock”></div>

Mouse Over & Mouse Out
Changing the div behavior based on mouse moments.

HTML Code

<div class=”grid”></div>
<div class=”grid”></div>
<div class=”grid”></div>
<div class=”grid”></div>

JavaScript
Here grid is the class name of div tags. Using this calling the selected DOM element.

//MouseOver
[].forEach.call(document.querySelectorAll(“.grid”), function(el) {
el.addEventListener(“mouseover”, function() {
this.classList.add(‘hover’);
});
});//MouseOut
[].forEach.call(document.querySelectorAll(“.grid”), function(el) {
el.addEventListener(“mouseout”, function() {
this.classList.remove(‘hover’);
});
});

CSS Code

.grid
{
width:180px; height: 100px;
background-color:#333333;display: block;cursor:pointer;
float:left;margin-right: 10px
}
.hover
{
background-color: #cc0000 !important
}

Live POST Update and Delete Records with Vanilla JS

A simple demo project, you can instantly upload and delete news feed without refreshing the page.

HTML Code
Update box with news feed result. Live Demo

<textarea id=”updateText”></textarea>
<input type=”button” id=”updateButton” value=”POST” /><div id=”newsFeed”>
//Record One
<div class=”feed”>
The Wall Script http://thewallscript.com
<a href=”#” class=”delete”>X</a>
</div>
//Record Two
<div class=”feed”>
9lessons Blog http://9lessons.info
<a href=”#” class=”delete”>X</a>
</div>
……..
……..
……..
</div>

Ajax Post
Contains JavaScript code querySelector(“#updateButton”).addEventListener(“click”, function(){}updateButton is the ID name of the button. Usingdocument.getElementById(“updateText”).value; calling update textbox value. I did simplified a function called vanillaGetPost, you will find this in vanillaFunctions.js. Take a look at the Live Demo

//Update content.
var newsFeed=document.getElementById(‘newsFeed’);
document.querySelector(“#updateButton”).addEventListener(“click”, function()
{
var p = document.createElement(“div”),
newsFeed = document.getElementById(“newsFeed”),
content = document.getElementById(“updateText”).value;
var html ;var data=’update=’+content;
vanillaGetPost(‘POST’, ‘post.php’, data, function(data)
{
var updateText= document.getElementById(“updateText”);
html='<a class=”delete” href=”#” onclick=”deleteButton(this)” title=”Delete”>X</a>’;
p.innerHTML = data+html; //User update with delete button HTML code.
newsFeed.insertBefore(p, newsFeed.firstChild);
vanillaFadeEffect(‘fadeIn’,newsFeed.firstChild, 1000);
updateText.value=”;
updateText.focus();
});});

post.php
You have to write database connection for inserting update.

<?php
if($_POST[‘update’])
{
echo htmlentities($_POST[‘update’]);
// Write database connection here.
}
?>

Delete Records
Using this.parentNode calling parent DIV DOM element and applying fadeOut effect.

//Delete click event
[].forEach.call(document.querySelectorAll(“.delete”), function(el)
{
el.addEventListener(“click”, function() {
var parent = this.parentNode;
vanillaFadeEffect(‘fadeOut’,parent, 1000); //vanillaFunctions.js
});
});

Final JavaScript Code
You can include all of the code here.

<script src=”js/vanillaFunctions.js”></script>
<script>
document.addEventListener(‘DOMContentLoaded’, function()
{
//Textarea focus
window.onload = function() {
document.getElementById(“updateText”).focus();
};var newsFeed=document.getElementById(‘newsFeed’);//Delete click event
…….
…….
…….

//Update content.
…….
…….
…….

});

function deleteButton(id)
{
var parent = id.parentNode;
//Delete Ajax
vanillaFadeEffect(‘fadeOut’,parent, 1000);
}
</script>

Download the script, you will find out vinillaFunctions.js

vanillaGetPost Function
Ajax function for POST and GET methods.

function vanillaGetPost(type, url, data, success)
{
if(type==’GET’)
{
url=url+’?’+data;
data=”;
}
var r = window.XMLHttpRequest ? new XMLHttpRequest() : newActiveXObject(“Microsoft.XMLHTTP”);
r.open(type, url, true);
r.onreadystatechange = function () {
if (r.readyState > 3 && r.status === 200){
success(r.responseText);
}
};
r.setRequestHeader(‘X-Requested-With’, ‘XMLHttpRequest’);
r.setRequestHeader(‘Content-Type’, ‘application/x-www-form-urlencoded’);
r.send(data);
return r;
}

vanillaFadeEffect Function
FadeIn and FadeOut animation effect.

function vanillaFadeEffect(effect, element, speed)
{
var A=0;
if(effect === ‘fadeOut’)
A=1;if ( ! element.style.opacity)
element.style.opacity = parseInt(A);var start = null;
window.requestAnimationFrame(function animate(timestamp) {
start = start || timestamp;
var progress = timestamp – start;

if(effect === ‘fadeOut’)
element.style.opacity = 1 – progress / speed;
else
element.style.opacity = progress / speed;

if (progress >= speed) {
if(effect === ‘fadeOut’)
element.style.display = ‘none’;
else
element.style.display = ”;

}
else
{
window.requestAnimationFrame(animate);
}
});

}

jQuery Primer in Html5

jQuery Primer in Html5

Writing JavaScript that works well across all major web browsers in a clean and concise way is a difficult chore. There are many libraries that make this process less painful, and jQuery is one of the most popular. It’s easy to use, has a wide array of existing libraries, and is a good fit for easily creating fallback solutions. This appendix introduces you to the parts of the jQuery library that we use elsewhere in the book. It’s not meant to be a replacement for jQuery’s excellent documentation, 1 nor is it going to be an exhaustive list of the features and methods available. It will, however, give you a good place to start jQuery Primer in Html5.

Loading  jQuery Primer in Html5

You can grab the jQuery library from the jQuery website 2 and link to the jQuery script directly, but we’ll load jQuery from Google’s servers, like this jQuery Primer in Html5:

<script type= "text/javascript"
charset="utf-8"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js" >
</script>

Browsers can make only a few connections to a server at a time. If we distribute our images and scripts to multiple servers, our users can download our pages faster. Using Google’s content delivery network has an additional benefit as well—since other sites link to the jQuery library at Google, our visitors may already have the library cached by their browser. As you probably already know, browsers use the full URL to a file to decide whether it has a cached copy. If you plan to work with jQuery on a laptop or on a computer without constant Internet access, you will want to link to a local copy instead jQuery Primer in Html5.
jQuery Basics jQuery Primer in Html5
Once you have loaded the jQuery library on your page, you can start working with elements. jQuery has a function called the jQuery( ) function. This one function is the heart of the jQuery library. We use this function to fetch elements using CSS selectors and wrap them in jQuery objects so we can manipulate them. There’s a shorter version of the jQuery( ) function, $();, and that’s what we use in this book. Throughout the rest of this appendix, I’ll refer to this function as “the jQuery function.” Here’s how it works: If you wanted to find the h1 tag on a page, you’d use the following jQuery Primer in Html5:

$("h1" );
$(".important" );

Take a look at that again. The only difference between those two examples is the CSS selector we used. The jQuery function returns a jQuery object, which is a special JavaScript object containing an array of the DOM elements that match the selector. This object has many useful predefined methods we can use to manipulate the elements we selected. Let’s take a look at a few of those in detail. Methods to Modify Content We use several jQuery methods to modify our HTML content as we work through this book.
Hide and Show to jQuery Primer in Html5
The hide( ) and show( ) methods make it easy to hide and show user interface elements. W e can hide one or many elements on a page like this jQuery Primer in Html5:

$("h1" ).hide();

To show them, we simply call the show( ) method instead. We use the hide( ) method throughout this book to hide page sections that only need to appear when JavaScript is disabled, such as transcripts or other fallback content. html, val, and attr We use the html( )method to get and set the inner content of the specified element. Here, we’re setting the content between the opening and closing h1 tags to “Hello World. ” The v al ( ) method sets and retrieves the value from a form field. for jQuery Primer in Html5 It works exactly like the html( ) method. The attr( ) method lets us retrieve and set attributes on elements. append, prepend, and wrap The append( ) method adds a new child element after the existing elements. Given we have a simple form and an empty unordered list, like this:

<form id= "add" >
<label for= "task" >Task</label>
<input type= "text" id="task" >
<input type= "submit" value="Add" >
</form>
<ul id= "links" >
</ul>

we can create new elements in the list by appending these new elements when we submit the form jQuery Primer in Html5.

$(function(){
$("#add" ).submit(function(event){
event.preventDefault();
var new_element = $( "<li>" + $( "#email" ).val() + "</li>" );
$("#links" ).append(new_element);
});
});

The prepend() method works the same way as the append() method but inserts the new element before any of the existing ones. The wrap() method wraps the selected element with the element represented by the jQuery object you specify jQuery Primer in Html5.

$("h1" ).css( { "color" : "red" ,
"text-decoration" : "underline" }
);
var wrapper = $( "#message" ).wrap("<div><h2>Message</h2></div>" ).parent();

We can define these one at a time, but we can also use a JavaScript hash to assign many CSS rules to the element: However, it’s not a good idea to mix style with scripts. We can use jQuery’s addClass( ) and removeClass( ) methods to add and remove classes when certain events occur. W e can then associate styles with these classes. We can change the background on our form fields when they receive and lose focus by combining jQuery events and classes.

$("input" ).focus(function(event){
$(this).addClass("focused" );
});
$("input" ).blur(function(event){
$(this).removeClass("focused" );
});

Events to jQuery Primer in Html5
We often need to fire events when users interact with our page, and jQuery makes this very easy. In jQuery, many common events are simply methods on the jQuery object that take a function. For example, we can make all the links on a page with the class of popup open in a new window like this jQuery Primer in Html5:

var links = $( "#links a" );
 links.click(function(event){
 var address = $( this).attr('href' );
 event.preventDefault();
 window.open(address);
 });

Inside our jQuery event handler, we can access the element we’re working with by using the this keyword. On line 3, we pass this to the jQuery function so we can call the attr( ) method on it to quickly retrieve the link’s destination address. We use the preventDefault( ) function to keep the original event from firing so it doesn’t interfere with what we’re doing. Bind Some events aren’t directly supported by jQuery, and we can use the bind( ) method to handle them. For example, when implementing the Drag and Drop part of the HTML5 specification, we need to cancel out the ondragover event. W e use the bind( ) like this jQuery Primer in Html5

target = $( "#droparea" )
target.bind('dragover' , function(event) {
if (event.preventDefault) event.preventDefault();
return false;
});

The Original Event on jQuery Primer in Html5

When we use any of the jQuery event functions like bind( ) or click( ), jQuery wraps the JavaScript event in its own object and copies only some of the properties across. Sometimes we need to get to the actual event so we can access those properties that didn’t get cloned. jQuery events give us access to the original event with the appropriately named originalEvent property. W e can access the data property of the onmessage event like this jQuery Primer in Html5:

$(window).bind("message" ,function(event){
var message_data = event.originalEvent.data;
});

Document Ready in jQuery Primer in Html5
The phrase “unobtrusive JavaScript” refers to JavaScript that’s kept completely separate from the content. Instead of adding onclick attribute butes to our HTML elements, we use event handlers like we just talked about in Section B.5, Events,We unobtrusively add behavior to our document, without modifying the document itself. Our HTML is not dependent on our users having JavaScript enabled. One drawback to this method is that JavaScript can’t “see” any of the elements in our document until they’ve been declared. We could include our JavaScript code in a script block at the bottom of the page after everything else has been rendered, but that isn’t reusable across pages. W e could wrap our code in JavaScript’s window.onLoad() event handler, but that event gets fired after all the content has loaded. This could cause a delay, meaning your users could be interacting with things before your events have been attached. W e need a way to add our events when the DOM is loaded but before it’s been displayed. jQuery’s document.ready function does exactly this, in a way that works across browsers. We use it like this jQuery Primer in Html5:

$(document).ready(function() {
alert("Hi! L am a popup that displays when the page loads" );
});

There’s a shorter, more compact version that we’ll be using throughout our code, which looks like this:

$(function() {
alert("Hi! L am a popup that displays when the page loads" );
});

We use this pattern in almost every example in this book so that we can easily, unobtrusively add fallback solutions to our projects. This is only a small sampling of what we can do with jQuery. Aside from the document manipulation features, jQuery provides methods for serializing forms and making Ajax requests and includes some utility functions that make looping and DOM traversal much easier. Once you become more comfortable with its use, you’ll no doubt find many more ways to use it in your projects to jQuery Primer in Html5.

Where to Go Next in Html5

Where to Go Next in Html5

Most of this book focuses on Most of this book focuses on things you can do right now, but there are some other things you will be able to start using very soon things you can do right now, but there are some other things you will be able to start using very soon that will make standards-based web development even more interesting, from 3D canvas support with W e b G L to new storage APIs, CSS3 transitions, and native drag-and-drop support. This chapter discusses some of the things on the horizon, so you can get an idea of what to expect. W e ’ ll talk about things that you may be able to use in at least one browser but don’t have good enough fallback solutions or are too far undefined to start working with right now: Where to Go Next in Html5.

CSS3 Transitons for Where to Go Next in Html5

Interaction invitations are important to good user experience design, and CSS has supported the :hover pseudoclass for some time so that we can do some basic interaction cues on our elements. Here’s some CSS markup that styles a link so it looks like a button

a.button{
padding: 10px;
border: 1px solid #000;
text-decoration: none;
}
a.button:hover{
background-color: #bbb;
color: #fff
}

When we place our cursor over the button, the background changes from white to gray, and the text changes from black to white. It’s an instant transition. CSS3 transitions 3 let us do quite a bit more, including simple animations that were possible only with JavaScript. For example, we can make this transition into a cross-fade by adding the following highlighted code to the style definition Where to Go Next in Html5:

a.button{
padding: 10px;
border: 1px solid #000;
text-decoration: none;
webkit-transition-property: background-color, color;
webkit-transition-duration: 1s;
webkit-transition-timing-function: ease-out;
a.button:hover{
background-color: #bbb;
color: #fff
}

On line 5 Where to Go Next in Html5, we specify what properties get the transition applied. In this case, we’re changing the background and foreground colors. We specify the duration of the animation on line 6, and we specify the transition’s timing function on line 7. Timing Functions The transition-timing-function property describes how transitions happen  over time in relation to the duration you’ve set. W e specify this timing function using a cubic Bezier curve, which is defined by four control points on a graph. Each point has an X value and a Y value, from 0 to 1. The first and last control points are always set to (0.0,0.0) and (1.0,1.0), and the two middle points determine the shape of the curve. A linear curve has its control points set to the two end points, which creates a straight line at a 45-degree angle. The four points for a linear curve are ( (0.0, 0.0), (0.0,0.0), (1.0, 1.0), (1.0, 1.0) ), and it looks like this Where to Go Next in Html5:

Where to Go Next PHP and ASP

Where to Go Next

A more complex curve, with points ( (0.0, 0.0), (0.42,0.0), (1.0, 1.0), (1.0, 1.0) ), called an ease-in curve, looks like this for Where to Go Next in Html5:

Where to Go Next PHP and ASP

Where to Go Next

This time, only the second point has changed, which is what causes the bottom-left part of the line to curve. Even more complex is the ease-in-out curve, which has a curve at the bottom and at the top, like this Where to Go Next in Html5:

Where to Go Next PHP and ASP

Where to Go Next

The points for this curve are ( (0.0, 0.0), (0.42,0.0), (0.58, 1.0), (1.0, 1.0) ).

We can specify these points right in the CSS property, or we can use some predefined ones like we did in our example. Our choices are default, ease-in, ease-out, ease-in-out, ease-out-in, and cubic-bezier, in which you set the points of the curve yourself. If you want the rate to be constant, you’d use linear. If you want the animation to start slow and speed up Where to Go Next in Html5, you’d use ease-in. If you want to learn a little more about making these curves, there’s a great public domain script 4 that shows you examples and helps you see the coordinates. Play around with transitions, but keep in mind that you want your interface to be usable first and pretty second. Don’t build transitions that frustrate the user, such as things that flicker or take too long to animate. You may also want to investigate CSS3 animations, 5 another method for changing CSS properties over time Where to Go Next in Html5.

Web Workers for Where to Go Next in Html5

Web Workers 6 are not part of the HTML5 specification, but you may find them useful if you need to do some background processing on the client side, so they’re worth mentioning. We use JavaScript for all of our client-side coding, but JavaScript is a single-threaded language—only one thing can happen at a time. If a task takes a long time, we force the user to wait until the task has finished. Web Workers solve this problem by creating a simple way to write concurrent programs. If we have a script called workesj.r that does some image processing, we can invoke it like this to Where to Go Next in Html5:

var worker = new Worker( "worker.js" );

Any JavaScript file can be launched as a worker, but in order for the worker to be independent, your worker script can’t access the DOM. That means you can’t manipulate elements directly. Our main script can send messages to the worker script using for Where to Go Next in Html5.

$("#button" ).click(function(event){
$("#output" ).html("starting..." );
worker.postMessage("start" );
});

Native Drag-and-Drop Support  for Where to Go Next in Html5

Letting users drag and drop interface elements is something we’ve been able to do with JavaScript libraries for quite a while, but the W3C has adopted Microsoft’s Drag and Drop implementation as part of the HTML5 specification. 7 It’s supported by Firefox, Safari, Internet Explorer, and Chrome, but in actuality it’s a mess with Where to Go Next in Html5. The implementation at first appears to be straightforward; we designate an element as “draggable,” we then designate an element that watches for a dropped object, and we execute some code when that happens. In reality, it’s not nearly that simple. To demonstrate, let’s create a simple drag-and-drop interface that lets us drag small images into a drop area that will load the larger version.

<div id="images">
<img src= "images/red_thumb.jpg"
data-large="images/red.jpg" alt="A red flower" >
<img src= "images/purple_thumb.jpg"
data-large="images/purple.jpg" alt="A white and purple flower" >
<img src= "images/white_thumb.jpg"
data-large="images/white.jpg" alt="A white flower" >
</div>
<div id="preview">
<p>Drop images here </p>
</div>

We are using custom data attributes heret o hold the source oft he larger version of our photos  to Where to Go Next in Html5.

Where to Go Next in Html5 PHP and ASP

Where to Go Next in Html5

Most of this book focuses on things you can do right now, but there are some other things you will be able to start using very soon

Next we’ll add some basic styles to float the two columns to Where to Go Next in Html5:

#images img{
-webkit-user-drag
}
#images{
float: left;
width: 240px;
margin-right: 10px;
}
#preview{
float: left;
width: 500px;
background-color: #ddd;
height: 335px;
}
.hover{
border: 10px solid #000;
background-color: #bbb !important;
}

At this point,Now let’s add some events so we can drag the photos.
Drag-and-Drop Events to Where to Go Next in Html5
We’ll need to work with several events related to dragging and dropping elements.

Event                      Description
ondragstart                Fires when the user starts dragging the object
ondragend                  Fires when the user stops dragging the object for any
                           reason
ondragenter                Fires when a draggable element is moved into a drop
                           listener
ondragover                 Fires when the user drags an element over a drop
                           listener
ondreagleave               Fires when the user drags an element out of drop
                           listener
ondrop                     Fires when the user drops an element into a drop
                           listener successfully
ondrag                     Fires when the user drags an element anywhere; fires
                           constantly but can give X and Y coordinates of the
                           mouse cursor

To Make Where to Go Next in Html5 That’s a total of seven events just to handle dragging and dropping elements, and some of the events have default behaviors. If we don’t override them, the whole thing fails. First, we need to define all of our list items as draggable.

var contacts = $('#images img');
contacts.attr('draggable', 'true');

We are adding the draggable HTML5 attribute. We could do this in our markup, but since we require JavaScript to do the interaction, we’ll apply this attribute with our script. When we drag the image, we want to grab the address of the large image and store it. We’ll bind to the ondragstart event, and to keep it simple and cross-platform, we’ll use jQuery’s bind( ) method Where to Go Next in Html5.

contacts.bind('dragstart', function(event) {
var data = event.originalEvent.dataTransfer;
var src = $(this).attr( "data-large" );
data.setData("Text" , src);
return true;
});

The specification provides a dataStorage mechanism that lets us specify the type of data and the data itself, which is passed along as part of the event. jQuery’s bind( ) method wraps the event in its own object, so we use the originalevent property on 2 to access the real event. W e store the URL to the image on the event by using the setData( ) method, using Text as the data type. Now that we can drag elements, let’s talk about how we fire events when the user drops the elements. Dropping Elements for Where to Go Next in Html5
We want our “To” form field to act as our drop target, so we’ll locate it and bind the drop event Where to Go Next in Html5.

var target = $('#preview');

target.bind('drop', function(event) {
var data = event.originalEvent.dataTransfer;
var src = ( data.getData('Text') );

var img = $( "<img></img>" ).attr("src" , src);
$(this).html(img);
if (event.preventDefault) event.preventDefault();
return(false);
});

We retrieve the image address we passed with the event using the get-Data( ) method on line 5, and we then create a new image element that we push into our content region. We need to cancel the default ondrop event so it won’t fire when our user drops the element onto the target. To do that, we need to use both preventdefault( ) and return false. Internet Explorer needs return false, and other browsers need preventDefault( ). If we try to use this in Chrome or Safari right now, it won’t work quite right. At a minimum, we have to override the ondragover element. If we don’t, our ondrag event won’t respond. So, we’ll do that by using this code Where to Go Next in Html5:

target.bind('dragover', function(event) {
if (event.preventDefault) event.preventDefault();
return false;
});

File Dragging
Moving text and elements around the page is just the beginning. The specification allows developers to create interfaces that can receive files from the user’s computer. Uploading a photo or attaching a file is as easy as dragging the file onto a specified target. In fact, Google’s Gmail supports this if you are using Firefox 3.6 or Chrome 5. If you want to explore this further, take a look at the excellent article 9 by Leslie Michael Orchard.
All Is Not Well to Where to Go Next in Html5
The behavior in various browsers is, to be kind, inconsistent. IE 8 works, but it breaks if we try to set the data type for setData( ) to Url instead of Text. Additionally, in order to support dragging of elements that are not images or links in Safari 4, we’d need to add additional CSS to our style sheet.

#contents li{
-webkit-user-drag
}

Throughout this book, we’ve discussed how important it is to keep style and behavior separated from content, and this flies right in the face of that concept.Don’t try dragging text onto form fields. Modern browsers already let you do this, but there’s no good way to override that behavior. As it stands, we can get much better results with much less code by using a JavaScript library that supports dragging and dropping like jQuery UI. 10 Even with a library, we still have one last thing to worry about: accessibility. The specification doesn’t say anything about how to handle users who can’t use a mouse. If we implemented drag-and-drop functionality on our interfaces, we’d need to develop a secondary method that didn’t require JavaScript or a mouse to work, and that method would depend on what we’re trying to do. This specification has a lot of potential, but it also has some things that need to be addressed. Use it if it makes sense, but ensure you don’t force your users into something they can’t use to Where to Go Next in Html5.

Web GL for Where to Go Next in Html5
We talked about the canvas element’s 2D context in this book, but there’s another specification in progress that describes how to work with 3D objects. The Web G L 11 specification isn’t part of HTML5, but Apple, Google, Opera, and Mozilla are part of the working group and have implemented some support in their browsers. Working with 3D graphics is well beyond the scope of this book, but the site Learning Web GL 12 has some great examples and tutorials. Indexed Database API to Where to Go Next in Html5
In this book, we talked about two methods for storing data on the client: Web Storage and W e b SQL Storage. The Mozilla foundation took issue with the W e b SQL specification, stating that they didn’t think it was a good idea to base the specification on a specific SQL engine. They introduced a new specification called the Indexed Database API, which is scheduled to become a standard of its own. 13 The Indexed Database API is a key/value store similar to the Web Storage APIs like localStorage and sessionStorage, but it provides methods for performing advanced queries. Unfortunately, at the time of writing, there are no implementations of this specification available, so it’s not even worth going into any implementation details because they will most likely change between now and the time it’s implemented. Firefox 4 and Chrome 7 are expected to include support. This is the specification you’ll want to watch closely, because Web SQL is at an impasse, and Mozilla has stated numerous times that it has no plans to ever implement W e b SQL in Firefox, because Mozilla is uncomfortable with the SQL dialect and doesn’t think that the specification should be based on one particular database implementation. The Web SQL specification uses the SQLite database dialect, which could change independent of the specification. It’s very likely that Internet Explorer will implement this specification as well, because Microsoft has taken an interest in its development.

Where to Go .Next PHP and ASP

Where to Go .Next

Client-Side FormV ali dati on to Where to Go Next in Html5
The HTML5 specification lists several attributes we can use to validate user input on the client side, so we can catch simple input errors before the user sends the requests to the server. We’ve been able to do this for years using JavaScript, but HTML5 forms can use new attributes to specify the behavior. W e can ensure that a user has required a form field by adding the required attribute like this:

<label for="name">Name </label>
<input type="text" name="name" autofocus required id="name">

Browsers can then prevent the form from submitting and display a nice error message, and we don’t have to write a single line of JavaScript validation. Opera does this right now, as you can see. This lets users fail early, without waiting for a server response to find out whether they made a mistake Where to Go Next in Html5. This behavior could be disabled or unavailable or just simply not correctly implemented, so you still need to make sure you have a server-side strategy for validating data. It’s definitely something to start thinking about now, though, because you can then easily locate the required fields and style the interface with CSS so that the required fields stand out from the rest for Where to Go Next in Html5. You can take this one step further witht he pattern attribute, which lets you specify a regular expression to ensure that the content meets your criteria.

<label for="name">Name </label>
<input type="text" name="name" autofocus required id="name">

Although Where to Go Next in Html5 no current browser uses this through the user interface, using this markup as the basis for a JavaScript validation library would be easy to implement.  Onward! It’s an exciting time to be a developer. This book just barely scrapes the surface of what the future holds for web developers. There’s so much more to the specifications, and I encourage you to dig deeper. I hope you take the things you learned here and continue to build and explore, watching the various specifications as you do so. Now go build something awesome to Where to Go Next in Html5!

Finding Yourself: From Geolocation

Finding Yourself: From Geolocation

Geolocation is a technique for discovering where people are, based on their computer’s location. Of course, “computer” really can mean smart phone, tablet, or other portable device as well as a desktop computer. Geolocation determines a person’s whereabouts by looking at their computer’s IP address, MAC address, Wi-Fi hotspot location, or even GPS coordinates if available. Although not strictly part of HTML5 the specification, Geolocation is often associated with HTML5 because it’s coming on the scene at the same time. Unlike W e b Storage, Geolocation was never part of the HTML5 specification. Like W e b Storage, it’s a very useful technology that is already implemented in Firefox, Safari, and Chrome. Let’s see how we can use it.

Locating Awesomeness for Finding Yourself: From Geolocation

We have been asked to create a contact page for the AwesomeCo website, and the CIO has asked whether we could show people’s location on a map along with the various AwesomeCo support centers. He’d love to see a prototype, so we’ll get one up and running quickly. We’ll use Google’s Static Map API for this because it doesn’t require an API key and we’re just going to generate a very simple map. AwesomeCo service centers are located in Portland, Oregon; Chicago, Illinois; and Providence, Rhode Island. Google’s Static Map API makes it really easy to plot these points on a map. All we have to do is construct an img tag and pass the addresses in the URL, like this to Finding Yourself: From Geolocation:

<img id= "map" alt="Map of AwesomeCo Service Center locations"
src="http://maps.google.com/maps/api/staticmap?
&amp;size=900x300
&amp;sensor=false
&amp;maptype=roadmap
&amp;markers=color:green|label:A|1+Davol+square,+Providence,+RI+02906-3810
&amp;markers=color:green|label:B|22+Southwest+3rd+Avenue,Portland,+OR
&amp;markers=color:green|label:C|77+West+Wacker+Drive+Chicago+IL">

We define the size of the image, and then we tell the Maps API that we did not use any sensor device, such as a GPS or client-side geolocation with the information we’re passing to this map. Then we define each marker on the map by giving it a label and the address. We could use a comma-separated pair of coordinates for these markers if we had them, but this is easier for our demonstration.
How to Be Found to Finding Yourself: From Geolocation. We need to plot our visitor’s current location on this map, and we’ll do that by providing another marker on the map by using our latitude and longitude for a new marker. W e can ask the browser to grab our visitor’s latitude and longitude, like this:

navigator.geolocation.getCurrentPosition(function(position) {
showLocation(position.coords.latitude, position.coords.longitude);
});

This method prompts the user to provide us with their coordinates. If the visitor allows us to use their location information, we call the showLocation( ) method. The showLocation( ) method takes the latitude and longitude and reconstructs the image, replacing the existing image source with the new one. Here’s how we implement that method for Finding Yourself: From Geolocation:

 var showLocation = function(lat, lng){
 var fragment = "&markers=color:red|color:red|label:Y|" + lat + "," + lng;
 var image = $( "#map" );
 var source = image.attr( "src" ) + fragment;
 source = source.replace( "sensor=false" , "sensor=true" );
 image.attr("src" , source);
 };

Rather than duplicate the entire image source code, we’ll append our location’s latitude and longitude to the existing image’s source. Before we assign the modified image source back to the document, we need to change the sensor parameter from false to true. We’ll do that on line 5 with the replace( ) method. When we bring it up in our browser, we’ll see our location, marked with a “Y” among the other locations. To see an example, take a look next page to Finding Yourself: From Geolocation.

Finding Yourself: Geolocation PHP and ASP

Finding Yourself: From Geolocation

Geolocation is a technique for discovering where people are, based on their computer’s location. Of course, “computer” really can

Falling Back to Finding Yourself: From Geolocation

As it stands, visitors to the page will still see the map with the locations of the AwesomeCo support centers, but we will get a JavaScript error if we try to load our page. W e need to detect support for geolocation before we attempt to get the visitor’s location, like this to Finding Yourself: From Geolocation:

if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(function(position) {
showLocation(position.coords.latitude, position.coords.longitude);
});
}else{
};

Google’s Ajax API 11 does location lookup, so it’s a great fallback solution. You will need to obtain an API key to use this on your site when you go live, but you don’t need one to try this locally.
Our fallback looks like this here to Finding Yourself: From Geolocation:

var key = "your_key" ;
 var script = "http://www.google.com/jsapi?key=" + key;
 $.getScript(script, function(){
 if ((typeof google == 'object') &&
 google.loader && google.loader.ClientLocation) {
 showLocation(google.loader.ClientLocation.latitude,
 google.loader.ClientLocation.longitude);
 }else{
 var message = $( "<p>Couldn't find your address.</p>" );
 message.insertAfter("#map" );
 };
 });

We’re using jQuery’s getScript( ) method to load the Google Ajax API. We then use Google’s ClientLocation( ) method on line 5 to get a visitor’s location and invoke our showLocation( ) method to plot the location on our map. Unfortunately, Google can’t geolocate every IP address out there, so we may still not be able to plot the user on our map; therefore, we account for that by placing a message underneath our image. Our fallback solution isn’t foolproof, but it does give us a greater chance of locating our visitor.
Without a reliable method of getting coordinates from the client, we’ll just need to provide a way for the user to provide us with an address, but that’s an exercise I’ll leave up to you.
The Future to Finding Yourself: From Geolocation
The techniques we talked about in this chapter, although not all part of HTML5 proper, represent the future of web development. We’ll be pushing many more things to the client side. Better history management will make Ajax and client-side applications much more intuitive. Web Sockets can replace periodic polling of remote services for the display of real-time data. Cross-document Messaging lets us merge web applications that usually would never be able to interact, and Geolocation will eventually let us build better location-aware web applications, which Finding Yourself: From Geolocation, become more and more relevant every day with the growing mobile computing market. Explore these APIs and keep an eye on their adoption. You may soon find these to be invaluable tools in your web development toolbox for Finding Yourself: From Geolocation.