Search Topic Here

Monday, 22 September 2014

JavaScript Frameworks



     The number of web applications being created and used has grown rapidly since the new millenium. And importantly, so has the sheer complexity of them -- specially on the front end. No more static pages.You have a ton of sections each interacting with each other and the server and yes, it's as complicated as it sounds and just as hard to pull off. Today, I'd like to talk about a few, choice JavaScript frameworks that aim to simplify front end application development.Creating responsive, fluid, and maintainable interfaces for web apps isn't as easy as one would imagine -- there is data to be sent back to the server and the results parsed, data stores to be updated, views to be re-rendered and so much else that needs to be done in the background. Desktop developers have it much easier with robust tools and well defined workflows. Us, poor web devs? We've been twiddling DOM elements, creating models by hand and pulling our hair out trying to keep everything synched.The monstrous rise in the number of web apps being built recently has really made it apparent that we need better tools and frameworks and the devs have responded with a staggering amount of solutions. Today, we're going to go over just a few of these. A couple of these are quite old but I'm certain you can learn a lot from perusing their code base.Sure, a few of these may be a little old but their code bases have lots of lessons to teach.

List of frameworks names
1.Sproutcore
2.Cappuccino
3.JavaScriptMVC
4.Asana Luna
5.Backbone.js
6.qooxdoo
7.sencha
8.Spine
9.ActiveJS
10.Eyeballs
11.Sammy
12.Choco

Wednesday, 2 July 2014

JavaScript Interview Questions and Answers


1.JavaScript Introduction:


JavaScript is the most popular programming language in the world. It is the language for HTML and the web, for servers, PCs, laptops, tablets, smart phones, and more.

2.What is JavaScript?

JavaScript is a Scripting Language.It is a lightweight programming language. JavaScript is programming code that can be inserted into HTML pages and it is executed by all modern web browsers.


3.What are JavaScript types? 

 Number, String, Boolean, Function, Object, Null, Undefined.

4.What is this keyword? 

 It refers to the current object.

5.How do you create a new object in JavaScript? 


var obj = new Object(); or var obj = {};

6.How do you convert numbers between different bases in JavaScript? Use the parseInt() function,

that takes a string as the first parameter, and the base as a second parameter. So to convert hexadecimal 3F to decimal, use parseInt ("3F", 16); 

7.What is the importance of <SCRIPT> tag? JavaScript is used inside <SCRIPT> tag in HTML

document. The tags that are provided provides the necessary information like alret to the browser for the program to begin interpreting all the text between the tags. The <script> tag uses JavaScript interpreter to handle the libraries that are written or the code of the program. JavaScript is a case sensitive language and the tags are used to tell the browser that if it is JavaScript enabled to use the text written in between the <Script> and </Script> tags.
The example is given as:
<HTML>
<HEAD>
<!--
<SCRIPT> // Starting of the scripting language
//Your code here
</SCRIPT> --> // End of the scripting language
</HEAD>
<BODY>
// your code here
</BODY>
</HTML>

8.What are the different objects used in JavaScripts?  

JavaScripts uses a hierarchical structure that applies to the objects in a document. There are some objects that show the relationship of one object to another using the language.
Window object: This is the topmost object in the hierarchy. It represent the content area of browser window that consists of HTML documents. Each frame is also a window that has some actions inside it.
Document object: This object gets loaded in a window and consists of objects of different kind in the model. It consists of the content that will be written in the script.
Form object: Form objects are used for more interaction with the users. It represents the form elements inside <FORM>...</FORM> tag.

9.What are the methods involved in JavaScript?

Method is an informative that gets performed over an action that is related to the object. Method either performs on some object or affect any part of the the script or a document. Object can have as many number of methods that have associations with other objects.
There is a method that is used by the JavaScript statement that includes a reference to an object this is given as:
document.orderForm.submit()
document.orderForm.entry.select()
These are the functions which perform the dynamic interaction with the user. The first statement execute the element when pressed submit button to send a form to a server. These two statements are related to only the form. The scripts that are invoked will have the write of the document as well and will be written as:
document.write(“Give the version “ + navigator.appVersion)
document.write(“ of <B>” + navigator.appName + “</B>.”)

10.Why is object naming important to use in JavaScript?  

Object naming is used to create script references to objects while assigning names to every scriptable object in the HTML code. The browsers that are script compatible looks for the optional tags and attributes that enables the assigning of a unique name to each object.
The example is:
 <form name=”dataEntry” method=get>
<input type=”text” name=”entry”>
<frame src=”info.html” name=”main”>
The names act as a nametags through which the elements can be easily identified and easily located by the browsers. The references made for each object includes the object hierarchy from the top down. References are used to include names of each object that are coming in the window object. The object naming conventions are easy way to loacte the objects and the linking between them can be done more comfortably.

11.What is the difference between == and === ?  The == checks for value equality, but === checks for

both type and value.

12.Difference between window.onload and onDocumentReady?

The onload event does not fire until every last piece of the page is loaded, this includes css and images, which means there’s a huge delay before any code is executed.
That isnt what we want. We just want to wait until the DOM is loaded and is able to be manipulated. onDocumentReady allows the programmer to do that.

13.How you define a function in javascript?

A function is a set of statements that will be executed when "someone" calls it.

Syntax:
function functionname()
{
some code to be executed
}

14.What are the javascript operators?Two types of operators are there..

a.Arithmetic Operators:
 Arithmetic operators are used to perform arithmetic operation between variables and/or values.
 Ex:   +,-,*,/,%,++,--
 b.Assignment Operators:
 Assignment operators are used to assign values to variables.
Ex:  =,+=,-=, *=,/=,%=

15.What are the javascript objects?"Everything" in JavaScript is an Object: a String, a Number, an Array, a Date....
In JavaScript, an object is data, with properties and methods.
Properties are values associated with an object.
Methods are actions that can be performed on objects.

16.How you declare a variable in javascript?You declare JavaScript variables with the var keyword.
Ex. var name;
 you can also assign a value to the variable when you declare it.
Ex. var name="blog";

17.What are the conditional statements in javascript?In JavaScript we have the following conditional statements:
if statement - use this statement to execute some code only if a specified condition is true
if...else statement - use this statement to execute some code if the condition is true and another code if the condition is false
if...else if....else statement - use this statement to select one of many blocks of code to be executed
switch statement - use this statement to select one of many blocks of code to be executed

 18.Tell me something about javascript validations?JavaScript can be used to validate data in HTML forms before sending the content to a server.
We have to check the following form data:
has the user left required fields empty?
has the user entered a valid e-mail address?
has the user entered a valid date?
has the user entered text in a numeric field?

19.What is the HTML DOM?DOM means Document Object Model.
When a web page is loaded, the browser creates a Document Object Model of the page.

20.What is browser object model?The Browser Object Model (BOM) allows JavaScript to "talk to" the browser.
The Window Object:
The window object is supported by all browsers. It represent the browsers window.
All global JavaScript objects, functions, and variables automatically become members of the window object.
Global variables are properties of the window object.
Global functions are methods of the window object.
Even the document object (of the HTML DOM) is a property of the window object:
window.document.getElementById("header");
is the same as:
document.getElementById("header");

21.How can you find the size of a window?Three different properties can be used to determine the size of the browser window (the browser viewport, NOT including toolbars and scrollbars).
For Internet Explorer, Chrome, Firefox, Opera, and Safari:
window.innerHeight - the inner height of the browser window
window.innerWidth - the inner width of the browser window
For Internet Explorer 8, 7, 6, 5:
document.documentElement.clientHeight
document.documentElement.clientWidth (or)
document.body.clientHeight
document.body.clientWidth

22.What does window.open() method?Opens a new window.

23.What does window.close() method?Closes the current window.

24.What does window.moveTo() method?Move the current window.

25.What does window.resizeTo() method?Resize the current window.

26.What is a Cookie? A cookie is a variable that is stored on the visitor's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With JavaScript, you can both create and retrieve cookie values.
Examples of cookies:
Name cookie - The first time a visitor arrives to your web page, he or she must fill in her/his name. The name is then stored in a cookie. Next time the visitor arrives at your page, he or she could get a welcome message like "Welcome John Doe!" The name is retrieved from the stored cookie
Date cookie - The first time a visitor arrives to your web page, the current date is stored in a cookie. Next time the visitor arrives at your page, he or she could get a message like "Your last visit was on Tuesday August 11, 2005!" The date is retrieved from the stored cookie.

27.What are the properties of window screen?The window.screen object can be written without the window prefix.
 screen.availWidth - It gives the available screen width.
screen.availHeight - It gives the available screen height.

28.What does window.history object?The window.history object can be written without the window prefix.
To protect the privacy of the users, there are limitations to how JavaScript can access this object.
Some methods:
history.back() - same as clicking back in the browser
history.forward() - same as clicking forward in the browser

29.  What does window history back?The history.back() method loads the previous URL in the history list.

30.What does Window History Forward?The history forward() method loads the next URL in the history list.

31.What are javascript Timing Events?It is possible to execute some code at specified time-intervals.This is called timing events
The two key methods that are used are:
setInterval() - executes a function, over and over again, at specified time intervals.
setTimeout() - executes a function, once, after waiting a specified number of milliseconds.

32.What is the syntax of setInterval() method?The setInterval() method will wait a specified number of milliseconds, and then execute a specified function, and it will continue to execute the function, once at every given time-interval.
Syntax:
window.setInterval("javascript function",milliseconds);
The window.setInterval() method can be written without the window prefix.
The first parameter of setInterval() should be a function.
The second parameter indicates the length of the time-intervals between each execution.

33.How to Stop the Execution of the function specified in the setInterval() method?The clearInterval() method is used to stop further executions of the function specified in the setInterval() method.
Syntax:
window.clearInterval(intervalVariable)
The window.clearInterval() method can be written without the window prefix.
To be able to use the clearInterval() method, you must use a global variable when creating the interval method:
myVar=setInterval("javascript function",milliseconds);

34.What is the syntax of setTimeout() method? The setTimeout() method will wait the specified number of milliseconds, and then execute the specified function.
Syntax:
window.setTimeout("javascript function",milliseconds);
The first parameter of setTimeout() should be a function.
The second parameter indicates how many milliseconds, from now, you want to execute the first parameter.

35.Give an example to setInterval() method?Example:
Alert "hello" every 3 seconds:
setInterval(function(){alert("Hello")},3000);

36. How to Stop the Execution of the function specified in the setTimeout() method.?The clearTimeout() method is used to stop the execution of the function specified in the setTimeout() method.
Syntax:
window.clearTimeout(timeoutVariable)
The window.clearTimeout() method can be written without the window prefix.
To be able to use the clearTimeout() method, you must use a global variable when creating the timeout method:
myVar=setTimeout("javascript function",milliseconds);
Then, if the function has not already been executed, you will be able to stop the execution by calling the clearTimeout() method.

37.What does window navigator object?The window.navigator object can be written without the window prefix.

38.What type of popup boxes are in javascript?JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box
 Alert box:
An alert box is often used if you want to make sure information comes through to the user.
When an alert box pops up, the user will have to click "OK" to proceed.
Syntax:
window.alert("sometext");
Confirm Box:
A confirm box is often used if you want the user to verify or accept something.
When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.
If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
Syntax:
window.confirm("sometext");
Prompt Box:
A prompt box is often used if you want the user to input a value before entering a page.
When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.
If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
Syntax:
window.prompt("sometext","defaultvalue");

39.Define Javascript Prototype?Prototype provides functions to make HTML DOM programming easier.
Like jQuery, Prototype has its $() function.
The $() function accepts HTML DOM element id values (or DOM elements), and adds new functionality to DOM objects.
Unlike jQuery, Prototype has no ready() method to take the place of window.onload(). Instead, Prototype adds extensions to the browser and the HTML DOM.
In JavaScript, you can assign a function to handle the window’s load event:
The JavaScript Way:
function myFunction()
{
var obj=document.getElementById("h01");
obj.innerHTML="Hello Prototype";
}
onload=myFunction;
The Prototype equivalent is different:
The Prototype Way:
function myFunction()
{
$("h01").insert("Hello Prototype!");
}
Event.observe(window,"load",myFunction);
Event.observe() accepts three arguments:
The HTML DOM or BOM (Browser Object Model) object you want to handle
The event you want to handle
The function you want to call

40.What are javascript frameworks/libraries?The most popular JavaScript frameworks:
jQuery
Prototype
MooTools
All of these frameworks have functions for common JavaScript tasks like animations, DOM manipulation, and Ajax handling.

41.Describe jQuery framework?jQuery is the most popular JavaScript frameworks on the Internet today.
It uses CSS selectors to access and manipulate HTML elements (DOM Objects) on a web page.
jQuery also provides a companion UI (user interface) framework and a plug-ins.
Many of the largest companies on the Web uses jQuery:
Google
Microsoft
IBM
Netflix

42.Describe Prototype framework? Prototype is a JavaScript library that provides a simple API to perform common web tasks.
API is short for Application Programming Interface. It is a library of properties and methods for manipulating the HTML DOM.
Prototype enhances JavaScript by providing classes and inheritance.

43.Describe MooTools framework?MooTools is also a framework that offers an API to make common JavaScript programming easier.
MooTools also includes some lightweight effects and animation functions.

44. Describe YUI framework?The Yahoo! User Interface Framework is a large library that covers a lot of functions, from simple JavaScript utilities to complete internet widgets.

45. Describe Ext JS framework?Customizable widgets for building rich Internet applications.

46.Describe Dojo framework?A toolkit designed around packages for DOM manipulation, events, widgets, and more.

47.Describe script.aculo.us framework?Open-source JavaScript framework for visual effects and interface behaviors.

48.What is CDN?CDN - Content Delivery Networks
You always want your web pages to be as fast as possible. You want to keep the size of your pages as small as possible, and you want the browser to cache as much as possible.
If many different web sites use the same JavaScript framework, it makes sense to host the framework library in a common location for every web page to share.
A CDN (Content Delivery Network) solves this. A CDN is a network of servers containing shared code libraries.
Google provides a free CDN for a number of JavaScript libraries, including:
jQuery
Prototype
MooTools
Dojo
Yahoo! YUI

49.What try,catch and throw statements does in javascript?

The try statement lets you to test a block of code for errors.
The catch statement lets you handle the error.
The throw statement lets you create custom errors.

50.When onLoad and onunload events are used in javascript?The onload and onunload events are triggered when the user enters or leaves the page.
The onload event can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.
The onload and onunload events can be used to deal with cookies.


Tuesday, 1 July 2014

Playing video in browser using Video Tag

Playing video in browser:

It is very easy to play videos in browser. HTML5 provides video tag <video>  which is one of the best feature in HTML5 for playing videos in browser.Most of the updated  browsers are supported this video tag.

Syntax for video tag:

<video controls>
<source src="path of video">
</video>

Example:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> Video tag </TITLE>
   </HEAD>

 <BODY>
  <video controls>
  <source src="http://media.w3.org/2010/05/sintel/trailer.mp4" >
  </video>
 </BODY>
</HTML>

OUTPUT:

Video tag
List OF attributes for video tag:

poster

Specifies an image to use while the video is unavailable (i.e. it hasn't loaded yet). This is typically an image of one of the first frames of the video. If supplied, the value must be a valid URL of an image.

preload

Specifies whether the video should be preloaded or not, and if so, how it should be preloaded. This attribute allows the author to provide a hint to the browser/user agent about what the author thinks will lead to the best user experience. This attribute may be ignored in some instances. For example, if the user has disabled preloading or if there are network connectivity issues.

Possible values:
*none
*metadata
*auto

Note that the autoplay attribute can overrride the preload attribute (since if the media plays, it naturally has to buffer first, regardless of the hint given by the preload attribute). Despite this, you can still provide both attributes.

autoplay

Specifies whether or not to start playing the video as soon as it can do so without stopping.
This attribute is a boolean attribute. Therefore, the mere presence of this attribute equates to a true value. You can also specify a value that is a case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace (i.e. either autoplay or autoplay="autoplay").

Possible values:

*[Empty string]
*autoplay

mediagroup For synchronizing playback of videos (or media elements). Allows you to specify media elements to link together. The value is a string of text, for example: mediagroup=movie. Videos/media elements with the same value are automatically linked by the user agent/browser.
An example of where the mediagroup attribute could be used is where you need to overlay a sign-languge interpreter track from one movie file over the top of another.

loop

Specifies whether to keep re-playing the video once it has finished.
This attribute is a boolean attribute. Therefore, the mere presence of this attribute equates to a true value. You can also specify a value that is a case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace (i.e. either loop or loop="loop").

Possible values:

*[Empty string]

loop

muted

Controls the default state of the video's audio output. If present, this attribute results in the audio output being muted (i.e. there is no sound) upon loading. This attribute will override the users' preferences. The user can then choose to turn on the sound if he/she so wishes. This helps users from being annoyed by loud sounds coming from the video as soon as the page/video starts loading. Users often close their browser when this happens. The 'mute' attribute aims to overcome this issue by having the video start off silently instead of loudly.
This attribute is a boolean attribute. Therefore, the mere presence of this attribute equates to a true value. You can also specify a value that is a case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace (i.e. either muted or muted="muted").

Possible values:

*[Empty string]

*muted

controls

Specifies whether or not to display video controls (such as a play/pause button etc).
This attribute is a boolean attribute. Therefore, the mere presence of this attribute equates to a true value. You can also specify a value that is a case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace (i.e. either controls or controls="controls").

Possible values:

[Empty string]
*controls

*width
Specifies the width, in pixels, to display the video.
Possible values:

[Non-negative integer] (for example, 300)

*height
Specifies the height, in pixels, to display the video.

Possible values:











JavaScript code for maintaining Graphic equalizer for audio songs

<!doctype html>
<html>
<head>
<style type="text/css">
div#mp3_player{ width:500px; height:60px; background:#000; padding:5px; margin:50px auto; }
div#mp3_player > div > audio{  width:500px; background:#000; float:left;  }
div#mp3_player > canvas{ width:500px; height:30px; background:#002D3C; float:left; }
</style>
<script>
// Create a new instance of an audio object and adjust some of its properties
var audio = new Audio();
audio.src = 'http://www.w3schools.com/html/horse.mp3';/*source for mp3 you can place your song location here*/
audio.controls = true;
audio.loop = true;
audio.autoplay = true;
// Establish all variables that your Analyser will use
var canvas, ctx, source, context, analyser, fbc_array, bars, bar_x, bar_width, bar_height;
// Initialize the MP3 player after the page loads all of its HTML into the window
window.addEventListener("load", initMp3Player, false);
function initMp3Player(){
document.getElementById('audio_box').appendChild(audio);
try {
    // Fix up for prefixing
    window.AudioContext = window.AudioContext||window.webkitAudioContext;
    context = new AudioContext();
  }
  catch(e) {
    console.log('Web Audio API is not supported in this browser');
  }
try{
//context = new webkitAudioContext(); // AudioContext object instance
analyser = context.createAnalyser(); // AnalyserNode method
canvas = document.getElementById('analyser_render');
ctx = canvas.getContext('2d');
// Re-route audio playback into the processing graph of the AudioContext
source = context.createMediaElementSource(audio);
source.connect(analyser);
analyser.connect(context.destination);
frameLooper();
}catch(e){console.log("errormsg????????????????????????"+e);}
}
// frameLooper() animates any style of graphics you wish to the audio frequency
// Looping at the default frame rate that the browser provides(approx. 60 FPS)
function frameLooper(){
window.webkitRequestAnimationFrame(frameLooper);
fbc_array = new Uint8Array(analyser.frequencyBinCount);
analyser.getByteFrequencyData(fbc_array);
ctx.clearRect(0, 0, canvas.width, canvas.height); // Clear the canvas
ctx.fillStyle = '#00CCFF'; // Color of the bars
bars = 100;
for (var i = 0; i < bars; i++) {
bar_x = i * 3;
bar_width = 2;
bar_height = -(fbc_array[i] / 2);
//fillRect( x, y, width, height ) // Explanation of the parameters below
ctx.fillRect(bar_x, canvas.height, bar_width, bar_height);
}
}
</script>
</head>
<body>
<div id="mp3_player">
  <div id="audio_box"></div>
  <canvas id="analyser_render"></canvas>
</div>
</body>
</html>

OUTPUT:

Getting keycode while pressing keyboard using javascript code

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title> Getting Keycode </title>
 
<script type="text/javascript">
document.onkeydown=getKeyCode;
 //window.onkeypress=getKeyCode;//remove cheste code vastundi 84, wen inserteing? no code in this case

function getKeyCode(event)
{
try{
var keyCode=event.keyCode;
document.getElementById("key").innerHTML=keyCode;
}
catch(ex)
{

document.getElementById("key").innerHTML=ex;

}
}


</script>
 </head>

 <body bgcolor='white'>
 <p style="font-size:50px;text-align:center;">The key code is  :::::::::::::::: <span id="key" style="font-size:50px"> </span></p>
 </body>
</html>

Output:


Getting Keycode

The key code is ::::::::::::::::


Monday, 30 June 2014

Form validation with CSS3


It is very easy to validate form by using CSS3 the below source code gives a  great validation


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> Form validation </TITLE>
   <style>
  body {
  font: 1em sans-serif;
  padding: 0;
  margin : 0;
}

form {
  max-width: 200px;
  margin: 0;
  padding: 0 5px;
}

p > label {
  display: block;
}

input[type=text],
input[type=email],
input[type=number],
textarea,
fieldset {
/* required to properly style form
   elements on WebKit based browsers */
  -webkit-appearance: none;

  width : 100%;
  border: 1px solid #333;
  margin: 0;

  font-family: inherit;
  font-size: 90%;

  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

input:invalid {
  box-shadow: 0 0 5px 1px red;
}

input:focus:invalid {
  outline: none;
}

  </style>
 </HEAD>

 <BODY>
  <form>
  <p>
    <fieldset>
      <legend>Title<abbr title="This field is mandatory">*</abbr></legend>
      <input type="radio" required name="title" id="r1" value="Mr" ><label for="r1">Mr. </label>
      <input type="radio" required name="title" id="r2" value="Ms"><label for="r2">Ms.</label>
    </fieldset>
  </p>
  <p>
    <label for="n1">How old are you?</label>
    <!-- The pattern attribute is not required on number field but
         it can act as a fallback for browsers which don't implement
         the number field but support the pattern attribute such as Firefox -->
    <input type="number" min="12" max="120" step="1" id="n1" name="age"
           pattern="\d+">
  </p>
  <p>
    <label for="t1">What's your favorite fruit?<abbr title="This field is mandatory">*</abbr></label>
    <input type="text" id="t1" name="fruit" list="l1" required
           pattern="[Bb]anana|[Cc]herry|[Aa]pple|[Ss]trawberry|[Ll]emon|[Oo]range">
    <datalist id="l1">
        <option>Banana</option>
        <option>Cherry</option>
        <option>Apple</option>
        <option>Strawberry</option>
        <option>Lemon</option>
        <option>Orange</option>
    </datalist>
  </p>
  <p>
    <label for="t2">What's your e-mail?</label>
    <input type="email" id="t2" name="email">
  </p>
  <p>
    <label for="t3">Leave a short message</label>
    <textarea id="t3" name="msg" maxlength="140" rows="5"></textarea>
  </p>
  <p>
    <button>Submit</button>
  </p>
</form>
 </BODY>
</HTML>

OUTPUT:

Form validation

Title*



Sunday, 29 June 2014

Html Dom



Every one confusing regarding HTML DOM(Document object Model).There no confusion HTML DOM meansimagining html document with  a  tree Structure with Parent and Child relationship.every one  knows that html is tag based and it  allows tags inside tags .

Ex:

<p>
    <b> Hello</b>
</p>

Here the bold tag <b> is inside para tag<p>
Now coming to the topic HTML DOM is introduced to change the properties of all the HTML elements dynamically by using java script.

The following Structue shows  basic HTML DOM:





Example Structure with table tag






here i will give a basic example for  changing visibility and hidden properties dynamically.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> New Document </TITLE>
<script>
function hidevisible(x)
{
if(x==1)
{
document.getElementById('text').style.visibility="hidden";
}

if(x==2)
{
document.getElementById('text').style.visibility="visible";
}
}

</script>
 </HEAD>

 <BODY>
 <p id="text">Hello How are u </p>
 <button onclick="hidevisible('1')">HIDE</button> <button onclick="hidevisible('2')" >visible</button>


 </BODY>
</HTML>

OUTPUT:
New Document
Hello How are u



Thursday, 26 June 2014

Design snake game with javascript

Code for snake game with  javascript:


<!doctype html>
<html>
<head>
<meta charset=UTF-8">
<meta name="description" content="Snake Game using HTML5 Canvas">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<title>Snake Game</title>
<style>
</style>
<script>

$(document).ready(function(){
var canvas = $("#canvas")[0];
var Context = canvas.getContext("2d");
var w = $("#canvas").width();
var h = $("#canvas").height();
var GameOver = $("audio#GameOver").get(0);
var GamePlay = $("audio#GamePlay").get(0);
var SnakeEating = $("audio#SnakeFood").get(0);
var cw = 10;
var direction;
var food;
var score;
var SnakeArray; 
$("button#play").hide();
$("button#Soundoff").hide();
function init()
{
if (GamePlay.paused)
         GamePlay.play();
direction = "right";
create_snake();
create_food();
score = 0;
Speed =100;
play();
}
function play()
{
   if(typeof game_loop != "undefined") clearInterval(game_loop);
game_loop = setInterval(paint, Speed);
allowPressKeys = true;
$("button#Soundoff").removeAttr('disabled');
$("button#SoundOn").removeAttr('disabled');

}
function pause()
{
clearInterval(game_loop);
allowPressKeys = false;
$("button#Soundoff").attr('disabled','disabled');
$("button#SoundOn").attr('disabled','disabled');
}
init();
function create_snake()
{
var length = 3; 
SnakeArray = [];
for(var i = length-1; i>=0; i--)
{
SnakeArray.push({x: i, y:0});
}
}

function create_food()
{
food = {
x: Math.round(Math.random()*(w-cw)/cw), 
y: Math.round(Math.random()*(h-cw)/cw), 
};
}

function paint()
{
YourScore="Your Score is: "+score;
   $("p#Score").html(YourScore);
Context.fillStyle = "blue";
Context.fillRect(0, 0, w, h);
Context.strokeStyle = "red";
Context.strokeRect(0, 0, w, h);
  var nx = SnakeArray[0].x;
var ny = SnakeArray[0].y;
if(direction == "right") nx++;
else if(direction == "left") nx--;
else if(direction == "up") ny--;
else if(direction == "down") ny++;
if(nx == -1 )
{
nx=w/cw-1;
}else if (nx==w/cw)
{
nx=0;
}
if(ny == -1)
{
ny=h/cw-1;
}
else if (ny == h/cw)
{
ny=0;
}

if(Ouroboros_Check(nx, ny, SnakeArray))
{
pause();
GamePlay.pause();
if(GameOver.paused)
 GameOver.play();
 alert("Game Over- Your Score : "+score);
 init();
 return;
}
if(nx == food.x && ny == food.y)
{
SnakeEating.play();
var tail = {x: nx, y: ny};
score++;
create_food();

}
else
{
var tail = SnakeArray.pop();
tail.x = nx; tail.y = ny;
}
SnakeArray.unshift(tail); 
for(var i = 0; i < SnakeArray.length; i++)
{
var c = SnakeArray[i];
paint_cell(c.x, c.y);
}
paint_cell(food.x, food.y);
}

function paint_cell(x, y)
{
Context.fillStyle = "white";
Context.fillRect(x*cw, y*cw, cw, cw);
Context.strokeStyle = "white";
Context.strokeRect(x*cw, y*cw, cw, cw);
}

function Ouroboros_Check(x, y, array)
{
for(var i = 0; i < array.length; i++)
{
if(array[i].x == x && array[i].y == y)
return true;
}
return false;
}

$("button#pause").click(function(){
$("button#pause").hide();
GamePlay.pause();
pause();
$("button#play").show();
});

$("button#Soundoff").click(function(){
$("button#Soundoff").hide();
GamePlay.play();
$("button#SoundOn").show();
});

$("button#SoundOn").click(function(){
$("button#SoundOn").hide();
GamePlay.pause();
$("button#Soundoff").show();
});

$("button#play").click(function(){
$("button#play").hide();
play();
GamePlay.play();
$("button#pause").show();
});

//Lets add the keyboard controls now
$(document).keydown(function(e){
if (!allowPressKeys){
    return null;
  }
var key = e.which;
switch(key)
{
case 37:
if(direction!="right") direction="left";
break;
case 38:
if(direction!="down") direction="up";
break;
case 39:
if(direction!="left") direction="right";
break;
case 40:
if(direction!="up") direction="down";
break;
default: 
         break;
}
})







})
</script>
</head>
<body align="center">
<h1>Snake Game</h1>
<canvas id="canvas" width="500" height="300">OOPS.. Upgrade your Browser</canvas>
<audio id="GamePlay" loop="loop" autoplay="autoplay">       
            <source src="GameGng.mp3" type="audio/mpeg" />
            Your browser does not support HTML5 audio.
        </audio>
<audio id="GameOver">       
            <source src="GameOver.mp3" type="audio/mpeg" />
            Your browser does not support HTML5 audio.
        </audio>
<audio id="SnakeFood">       
            <source src="SnakeEating.mp3" type="audio/mpeg" />
            Your browser does not support HTML5 audio.
        </audio>
<br/>
<strong><p id="Score"></p></strong>
<button id="pause"><img src="pause.jpg" alt="Pause"/></button>
<button id="play"><img src="Play.jpg" alt="Play"/></button>
<button id="Soundoff"><img src="SoundsOff.jpg" alt="SoundOFF"/></button>
<button id="SoundOn"><img src="SoundsOn.jpg" alt="SoundON"/></button>
</body>

OUTPUT: Snake Game

Snake Game

OOPS.. Upgrade your Browser


Sunday, 25 May 2014

JavaScript Code for Searching and displaying youtube video in your website

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> search </TITLE>
  <META NAME="Generator" CONTENT="EditPlus">
  <META NAME="Author" CONTENT="">
  <META NAME="Keywords" CONTENT="">
  <META NAME="Description" CONTENT="">
  <style >
 
  </style>
 </HEAD>

 <BODY>
 <br><br><script >
 function search(){
 document.getElementById("frame").innerHTML="&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<iframe width='450' id='YT' height='450' src='http://www.youtube.com/embed/?listType=search&list="+document.getElementById("querystring").value+" 'frameborder='0'></iframe>";

 }
 </script>

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
 <input type="text" id="querystring"><button onclick="search()">Search</button>
 <br><br>

 <div id="frame" >

&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
  <iframe width='500' id="YT" height='500' src='http://www.youtube.com/embed/?listType=search&list=New telugu trailer' frameborder='0'  style="align:center;"></iframe>
 </div>
 </BODY>

</HTML>

OUTPUT:

search