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);
}
});

}

Browser Notifications Display from Web Application

Browser desktop notification system, using this you can push notifications for event reminders, message information like whatsapp to desktop users in realtime from your web project. Very few line of JavaScript code, that can help you to interact with browser notification system. I have implemented this for 9lessons.info, you will find a most popular article notification for every 3 minutes. Take a quick look a the live demo.

browser PHP and ASP

Note: Try this demo with Chrome and Firefox

Start Browser Notification:
This code will initialize the browser notification system, read more about Vanilla JS(Plain JavaScript)

document.addEventListener(‘DOMContentLoaded’, function ()
{if (Notification.permission !== “granted”)
{
Notification.requestPermission();
}

});

Push Notification:
This function will help you to push notification data, here you have to modify iconURL. You can pass title, description and URL values.

function notifyBrowser(title,desc,url)
{if (Notification.permission !== “granted”)
{
Notification.requestPermission();
}
else
{
var notification = new Notification(title, {
icon:’http://YourWebsite.com/logo.png’,
body: desc,
});

/* Remove the notification from Notification Center when clicked.*/
notification.onclick = function () {
window.open(url);
};

/* Callback function when the notification is closed. */
notification.onclose = function () {
console.log(‘Notification closed’);
};

}
}

Firefox mozilla notification documentation

Demo Array:
The array contain most popular articles on 9lessons.info

var articles = [
[
“Vanilla JS Browser Default Java Script.”,
“http://www.9lessons.info/2015/09/vanilla-js-browser-default-java-script.html”
],
[
“Facebook Style Background Image Upload and Position Adjustment.”,
“http://www.9lessons.info/2015/02/facebook-style-background-image-upload.html”
],
[
“Create a RESTful services using Slim PHP Framework”,
“http://www.9lessons.info/2014/12/create-restful-services-using-slim-php.html”
],[
“Pagination with Jquery, PHP, Ajax and MySQL.”,
“http://www.9lessons.info/2010/10/pagination-with-jquery-php-ajax-and.html”
],
[
“Ajax Select and Upload Multiple Images with Jquery”,
“http://www.9lessons.info/2013/09/multiple-ajax-image-upload-jquery.html”
],
……
……
……
];

J query:
Contains javascipt code. $(“#notificationButton”).click(function(){}- notificationButtonis the ID name of input button.

<script src=”https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js”></script>
<script>
$(document).ready(function()
{
$(“#notificationButton”).click(function()
{
var x = Math.floor((Math.random() * 10) + 1); /* Random number between 1 to 10 */
var title =articles[x][0];
var desc =’Most popular article.’;
var url =articles[x][1];
notifyBrowser(title,desc,url);
return false;
});
});
</script>
//HTML Code
<input type=”button” id=”notificationButton” />

Vanilla JS:
Plain JavaScript

<script>
document.addEventListener(‘DOMContentLoaded’, function()
{
document.querySelector(“#notificationButton”).addEventListener(“click”,function(e)
{
var x = Math.floor((Math.random() * 10) + 1); /* Random number between 1 to 10 */
var title =articles[x][0];
var desc =’Most popular article.’;
var url =articles[x][1];
notifyBrowser(title,desc,url);
e.preventDefault();
});
});
</script>
//HTML Code
<input type=”button” id=”notificationButton” />

Set Timeout:
Contains simple JavaScript code, calls after 2 minutes. Here you can modify milliseconds values.

<script>
setTimeout(function(){
var x = Math.floor((Math.random() * 10) + 1); /* Random number between 1 to 10 */
var title =articles[x][0];
var desc =’Most popular article.’;
var url =articles[x][1];
notifyBrowser(title,desc,url);
}, 120000); //calls every 2 minutes
</script>

Over and Over with the for Loop

with the for Loop

Computers are great at performing tasks over and over again with the for Loop(that’s part of their charm—they can do the grunt work). One of the ways JavaScript lets you perform tasks over and over is with the for loop, which you can use to execute code multiple times (such as displaying  “Happy Birthday!” 25 times for a 25-year-old). Here’s what the for loop looks like formally speaking (as before, the parts in square brackets are optional, and you replace the parts in italics with your own JavaScript):

for ([initial-expression]; [condition]; [increment-expression]) {
statements
}

You usually use a for loop with a loop index, also named a loop counter. A loop index is a variable that keeps track of the number of times the loop has been executed. In the initialexpression part, you usually set the loop index to a starting value; in the condition part, you test that value to see if you still want to keep on looping; and the increment-expression lets you increment the loop counter with the for Loop.

Here’s an example with the for Loop, for.html. This example adds the numbers from 1 to 100—something you’d probably be pleased to let a computer do rather than add up all the numbers yourself. In this case, you want the computer to loop 100 times, which you can do with a for loop and a loop index variable like this:

var loopIndex;
for(loopIndex = 1; loopIndex <= 100; loopIndex++) {
-
-
-
}

Here with the for Loop

the variable loopIndex starts at 1, and at the end of each time through the loop, 1 is added to loopIndex with the expression loopIndex++, because the JavaScript ++ operator increments the variable you apply it to by one (the — operator decrements the variable you apply it to by 1). And the loop above stops when the value in loopIndex is greater than 100 (that is, the loop keeps looping while loopIndex <= 100). So to add the numbers from 1 to 100, you just have to add this code:

var loopIndex;
var total = 0;
for(loopIndex = 1; loopIndex <= 100; loopIndex++) {
total += loopIndex;
}

Here’s what it looks like in a web page with the for Loop, for.html:

<html>
<head>
<title>Using the for loop</title>
<script language="javascript">
function display()
{
var loopIndex;
var total = 0;
for(loopIndex = 1; loopIndex <= 100; loopIndex++) {
total += loopIndex;
}
document.getElementById('targetDiv').innerHTML =
"The total of 1 to 100 is " + total;
}
</script>
</head>
<body>
<h1>Using the for loop</h1>
<input type="button" onclick="display()" value="Click Here">
<div id="targetDiv">
</div>
</body>
</html>

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="https://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.