Auto-Generating Z-Indexes with SASS


Z-index management is one of the most useful things that SASS gives us. We no-longer need to fiddle with numbers, and the order is presented in a direct, visual way. Introducing the mixin:

@mixin u-z-index
    $me: "#{&}";
    $z-val: index($z-list, $me);
    z-index: $z-val * 10 + 100;

This is how it’s used:

    @include u-z-index;

Managing Z-indexes is now as simple as adding the mixin to your element, then adding the selector to the list within the mixin. You can change the z-index order by moving the selector lines around in the list. The final z-index will be a result of its index within the list, times 10, plus 100. I start my lists at 110 as there are some javascript libraries that auto-generate z-indexes between 1 and 100. You can remove that part if you don’t need it.

This functionality is achieved by others in different ways, you should check them out too and decide what would work best for your project. Remember, keep it simple unless you can justify the need for added complexity.

Other examples:

Some of these other examples add z-index ‘categories’ and assign each element to a category. I prefer to do without categories and ensure that each element has a different z-index. These techniques are a great example of how to use new technology to improve the quality of code.

CSS Preprocessors – Write LESS and put some SASS into your styling


As a website styler, it can get quite frustrating in this world of CSS, having to endlessly replicate code lines just to target another selector below the one you are styling, it can add up to literally thousands of lines of code, unnecessary code as well which you will eventually have to sift through just to find that line height that seemed like a good idea to set at the time…

Enter the CSS Preprocessor, this little tool will change your styling world forever. Just a precursor though, whilst I will be explaining LESS in this blog post, you can apply the same theory to almost any CSS Preprocessor.

I was forced to use LESS about a year or two ago when looking into using the Bootstrap framework, at first I hated it, it seemed so overly unnecessary, and it didn’t seem to help me at all.

After getting frustrated and just dumping my normal CSS within the LESS files, I realised there must be a reason that such a juggernaut like Bootstrap uses such a tool like this. So I did some homework.

If you are looking for some good tutorials then the best place to start is usually the site where the code comes from. So I made my way to and started to read up.

It’s really quite simple, each level you want to select can be nested and styled within itself.

Take this code snippet for example.

body {
background: url(‘/some/awesome/picture.jpg’);
padding: 10px 20px;
body #header {
background: #000;
color: #fff;
body #header p {
font-size: 14px;
color: #666;
body #header p span {
background: #000;
color: #fff;

Quite cumbersome when you have to write out the same classes again and again just to target another selector… If this were done with LESS you can squeeze it into the following.

body {
background: url(‘/some/awesome/picture.jpg’);
padding: 10px 20px;
#header {
background: #000;
color: #fff;
p {
font-size: 14px;
color: #666;
span {
background: #000;
color: #fff;

At first this might seem pointless, you aren’t actually saving any lines of code, but it’s the fact that you don’t have to keep retyping (or copying and pasting) the same selectors again and again.

Also this way you can group your styling and have much cleaner and leaner code.

This is just the tip of the iceberg with LESS though, there is MUCH more that can be done with it. The point of LESS is to use LESS code.

Mixins as they are known in LESS language are snippets of code that you can re-cycle, so you don’t have to keep writing out the same thing time and time again and they also mean you will never have to use that hacky method of search and replace EVER (seriously I mean it).

Take the example below:

.button {
color: #fff;
background: #ff000;
.header {
color: #fff;
background: #ff000;
.page-title {
color: #fff;
background: #ff000;
.brand-highlight {
color: #fff;
background: #ff000;

This snippet is one that is used a lot when you are dealing with a business brand colour, for this example the brand colour is red. Now let’s say you wanted to re-use this in an entire new site, but the new brand colour was blue… with CSS you would whip out the old search and replace and hope to god that:

  1. All the spacing was the same…
  2. The exact same hex code was used every single time…
  3. If there were any variations, again, the same hex code was used
  4. There was only 1 style sheet… otherwise you are in for trouble

These are just the things that spring to mind, and I can guarantee that every time you do this, there will be some stupid variation that a designer put in, like a drop shadow that is an alpha with some transparency or a tint colour or SOMETHING like that.

Again this is where LESS will save you literally HOURS of time. The mixin is set once and then is reused throughout the project and can be manipulated without ever having to change the original colour.

See the snippet above, used below with LESS

@brand-primary: #ff000;
.button {
color: #fff;
background: @brand-primary;
.header {
color: #fff;
background: @brand-primary;
.page-title {
color: #fff;
background: @brand-primary;
.brand-highlight {
color: #fff;
background: @brand-primary;

To make this even more advanced you can use:

.brand-highlight {
color: #fff;
background: @brand-primary;
text-shadow: darken(@brand-primary, 80%);

So now when you change the mixin colour at the start of the code, it will flow through beautifully and change all the styling with one fell swoop (take that Search and replace!)

To touch on the above code as well, LESS also allows you to have the ability to apply mathematical functions to any style so you can have pixel point accuracy, most designers use percentage for opacity or colour changes (like a highlight or hover colour) and this way you can apply it in the same way, so when the client says “just a little lighter” rather than whipping out your hex colour palette, just change the percentage to match and it’s all done for you.

There is A LOT more you can do with these processors, but I thought I would share some easy to explain features which have really changed the way I style.


A complex program needs memory

LESS is no exception, you will need your own development server, and you don’t want to be coding in LESS on a live site. It uses resources which converting all the coding to CSS and it is not shy about gobbling them all up. But with that, it will make sure you use proper web development practices, develop on a dev server, save all your changes, and then put them live.

Learning LESS is hard at first

It can be difficult if like me, you can be styling for well over 10 years… I was set in my ways, but over the last 2 years, I have relearnt and been able to take advantage of LESS. It’s not ALWAYS the right time to use LESS If you have a site that you don’t really have access to obtain a dev copy of, or it is quite a simple design, sometimes a CSS prepocessor might not be the right option, so you need to pick and choose your battles. Have fun! Links to some CSS Preprocessors:

  1. Sass –
  2. Less.js –
  3. Stylus –
  4. CSS-Crush –
  5. Myth –
  6. Rework –



The days of pure HTML, CSS and Javascript are over. Now we must learn CSS pre-processors and frameworks, multiple Javascript libraries (usually based on jQuery) HTML templating engines based in Javascript, task runners such as grunt and gulp, etc. With all of these tools available, and becoming an ‘industry standard’, it’s easy to misuse them and make a real mess of your website coding.

The reality is, you don’t need any add-on technologies. You can always create websites with highly organised, easily maintainable code, even when using the base technologies.

Modern web development often involves over-engineering. By this, I mean that too much time is spent on setting things up, writing and configuring tools and finding ‘smart’ ways of doing things instead of just doing what needs to be done in a logical manner.

CSS Preprocessors


We all know the rule that selectors shouldn’t be nested more than 4 levels deep. However, I disagree with this, as I find that nesting selectors at all will make the code less readable. It’s easy to scan code in a vertical manner, but when my eyes need to also scan horizontally, it makes scanning much less efficient.

If I am looking through a style sheet and I find a class nested a few levels deep, I need to know the parent selectors to understand how the class is being applied. I need to scroll up to see the parent selector, then scroll up again to see its parent selector, then again. It’s not immediately obvious or straight-forward how it will be applied, I need to scan entire blocks of code to understand one line. It’s not a problem if the blocks are small, but there are usually quite a few child selectors under the parent block.

What I often see is a top-level class being used like a namespace. While it may seem neat to organise code this way, it takes more time and effort to understand it. It doesn’t add anything to the code organisation that you couldn’t do with a few line-breaks or comments. The only benefit is reduction of selector repetition. If organising CSS like programming code was that important, we would have adopted JSS instead of CSS.

I prefer to only use nesting for states and, sometimes, pseudo elements.

Media Queries

Another issue I sometimes come across is the use of multiple repeated media queries. Should each selector have its own media query? What about when they’re nested? It can become a bit messy and hard to see the big picture if so much functionality is separated into multiple super small media queries.

I prefer to use a set of media queries per ‘module’ or ‘feature’, so I don’t have a million media queries and yet I also don’t have one big monolithic set of media queries at the end of the file.

Useless complexity

One of the worst examples of investing time into making something that is often unnecessary, useless or even detrimental, would be the idea of wrapping media queries in pre-processor functions or mixins. I can understand the desire to use this when you have a lot of very complex media queries, used often. However, in most cases it’s just not necessary. You will see a line of code like this:

@include respond-to($medium) { }

What exactly does this do? It’s media query related, but you will need to go looking for the definition of $medium to know if it is just a pixel value, a query or a key relating to a keymap. Either way, you need to find the query text, the associated pixel values, how to use this function and what options are already available.

You will need to read and understand the definition of the function to see how it implements these variables. Does it use min-width or max-width as a default? Does it have default functionality?

What benefits does this function hold over a set of variables? You don’t need to type the word ‘@media’ anymore, instead you need to write ‘respond-to’. This is replacing a universally understood piece of fundamental CSS with a lesser-known custom implementation.

It’s always interesting to see what you can do with the tools available and how far you can go. However, we are replacing a straight forward set of readable statements with a slightly more cryptic line of code that needs to be investigated and understood by a programmer.

The benefit of this technique relies largely on how complex your media queries are, and how often your media queries are used. For sites that use simple media queries, storing the pixel value in a variable will be just as effective. For slightly more complex queries, you can store the entire query in a variable.

The creator of this technique warns his readers about finding a balance and picking the right tool for the job. I’ve seen this technique used in a way that is detrimental to the project many times.

Before using this technique, you need to consider if it’s the right thing to use for your project. Consider your development environment, project size, tooling and style of coding. Don’t just use this because it’s ‘good / standard practice’. Use it only if it suits your project.



When you want to read a book, you go to the library and borrow one. However, common practice with Javascript is to borrow the whole library just to read one book. Often, libraries like Bootstrap are included and used just for one feature. One feature that you could write in three lines of code. It’s important to justify the inclusion of an entire library before you do so.

Insane code

A previous company that I used to work for, had outsourced a project to an overseas company. One feature of the website was a little call to action button that would stick to the top right of the screen when the user scrolled past a certain point.

The developers had implemented this by using a collision detection system about a page long. It detected when any part of the element collided with the banner above it, so they knew when to remove the fixed position if the user was scrolling upwards. It was probably ripped from some game engine. I’m surprised they didn’t go one further and program some sort of self-learning AI to achieve the same task.

How many lines of code would it take you to implement that functionality?

Lack of programming knowledge

If (I == true)
     I = false
 } else if (I == false) {
     I = true

Actual code. From a teacher in a web development course. This was back in 2008. It’s memorable, but not in a good way.

This is not as common nowadays as most people know about the ‘not’ operator, but I have seen people implement code to replicate the functionality of the ‘modulus’ operator.

It’s important to know the features of the languages you use.


There are many motivations to complicate your code. To improve maintainability, improve functionality, boredom, being a smartypants, to annoy people for fun etc. However, keep in mind that in a year’s time, you may be the one working with your own code, cursing the developer who made this mess, only to find out that it was you who screwed you over. Yes, I’ve been in that situation, which is how I know. It’s also why I do things simpler and, for the lack of a better term, slightly more old-school than most people when possible.

Best framework for creating mobile applications with HTML, CSS, and JavaScript…

Let’s assume you are trying to create a location-based mobile application for Android. What framework will you prefer? Phonegap… ???
OR any better option?
As per my study, we can use PhoneGap to wrap HTML/CSS/JS mobile web apps to create native apps for iOS, Android, Blackberry, etc. There are many other Frameworks, Tools, and Libraries for Creating Mobile Applications. And from My experience I would be very careful with HTML Mobile Framework. They tend to be heavy and require lot of CSS/HTML elements.
I will suggest to use jQuery and target webkit (iOS and Android) and try to optimize your DOM and UI component as much as possible. Then, you can degrade for other browsers.

If you are building an offline application, you can use a MVC. Anyway, the rule is that the less framework you use the better you are. So, pick carefully, and make sure they are not kitchen sink.

And here is the List of Top 10 Frameworks To Build Mobile Application With HTML, CSS & JavaScript: 

1. JQuery Mobile
jQueryMobile is a robust mobile development framework to build cross-mobile-platform app. 

2. Cordova / PhoneGap
PhoneGap is essentially based on Cordova. Cordova/Phonegap provides a set JavaScript APIs that connect to the device’s native functions such as Camera, Compass, Contacts, and Geolocation. Cordova/Phonegap lets us build a mobile application without the native programming language; instead we can use a framework like jQuery Mobile. 

3. Sencha Touch
Sencha Touch is a mobile framework powered by HTML5 and CSS3, providing APIs, animations, and components that are compatible with the current mobile platforms and browsers. 

4. Ratchet
Ratchet was originally used by Twitter as an internal tool to create their mobile app prototype which is then released publicly as an open source project. 

5. Ionic
If you are concerned with your app performance, Ionic is the right framework for you. Ionic is an HTML5 mobile framework with focus on performance, by leveraging hardware acceleration, and it requires no third-party JS library. 

6. Lungo
Lungo is a lightweight mobile framework based on HTML5 and CSS3. 

7. JQT
jQT is a Zepto plugin for mobile framework primarily designed for Webkit browsers. 

8. Junior
Junior is also a Zepto plugin for building a mobile app similar to jQT. 

9. Jo
Jo supports a wide variety of mobile platforms including Tizen and Chrome OS. Jo also comes with a starter, that is powered by CSS3, so it makes it easy for web developers at any level of experience to grasp and start styling their apps. 

10. Famo.Us
A new kid on the mobile framework block,
 promises to eliminate HTML5 performance issue on mobile devices with its lightweight JavaScript engine (only 64k). 

How to use CSS in a HTML document

We are much aware what is CSS, and it’s uses in previous blogs, Now Let’s try to understand How to use CSS or Style sheet in a HTML document. CSS present the good presentation in a document and Web page or App.
We can use Style sheet using three methods:
·        We can use an external style sheet, either by importing it or by linking to it.(External Style Sheet)
·        Directly embed a document-wide style in the head element of the document. (Document – Wide Style)
·        Set an inline style rule using the style attribute directly on an element. (Inline Style)
Each of these style sheet approaches has its own pros and cons, as listed below:

   Now let’s some work using all three method

1.       External Style Sheet: An external style sheet is simply a plain text file containing CSS style   
Rules. The common file extension .css indicates that the document provides style sheet information. As an example, the following CSS rules can be found in a file called sitestyle.css, which defines a style sheet used site-wide:
After above sheet we will work with HTML doc…
So now we are done with both files Let’s see the Output:
CSS is, at least theoretically, not the only style technology we could use, though as it stands, by default, most browsers assume that CSS is being used. We set type to be specific but that may get a bit redundant. The HTML specification suggests you can set a default style sheet language in the head element of the document by using the <meta> tag, as
shown here,
<meta http-equiv=”Content-Style-Type” content=”text/css”>
by outputting this value in the HTTP headers delivered to a site. Interestingly, many sites
set the <meta> tag and use the type attribute, which is particularly appropriate as of this
edition’s publication as the specification dictates that the type attribute must be set and
thus the W3C validator will complain if the attribute is not set regardless of the appearance
of the <meta> tag.
2.      Embedding Style Sheets: The second way to include a style sheet is to embed it. When you embed a style sheet, you generally write the style rules directly within the document with a <style> tag found within the <head> </head> of the document.
The basic syntax of the <style> tag is as follows:
<style type=”text/css” media=”all | print | screen” >
* Style Rules….*
Now let’s do an Example:

You can have multiple occurrences of the style element within the head of the document, and you can even import some styles with these elements.
OutPut for the above code:

While this technique is common practice and used for script masking as well, there are some subtle issues, particularly when including non-comment-friendly content like multiple dashes or trying to address XML strictness. (McGraw-Hill CSS)
3.      Inline Styles:  Instead of using a style sheet for a whole page, you can add style information directly within a single element. Suppose you want to set one particular <h1> tag to render in extra-large, green, Arial font. You could quickly apply the style to only the tag in question using its style attribute, which is a core attribute common to nearly any HTML element.
As an example, the following markup shows an inline style applied to a heading:
<h1 style=”font-size: xx-large; font-family: Arial; color: green;”>
This sort of style information doesn’t need to be hidden from a browser that isn’t style sheet-aware, because browsers ignore any attributes that they don’t understand.
Although using inline styles seems to be an easy route to using CSS, it does have a number of drawbacks. The largest problem is that inline rules are bound very closely to a tag. If you want to affect more than one <h1> tag, you have to copy and paste the style attribute into every other heading of interest. The separation of markup from CSS presentation is not optimal with an inline style. However, for quick and dirty application of CSS rules, this might be appropriate, particularly for testing things out.
The second and lesser-known concern with inline CSS rules is that you simply cannot perform every task with them. For example, if you want to change the look of various link states, this is easily accomplished in a document-wide or linked style sheet with pseudo-class rules like
a:link {color: blue; text-decoration: none;}
a:visited {color: red; text-decoration: none;}
a:hover {color: red; text-decoration: underline;}
a:active {color: red; text-decoration: none;}
However, if you attempt to put such rules in an <a> tag, how are other states indicated? The simple example here would appear to set the color to blue for any state:
<a href=”” style=”color: blue;”>Inline Link Styles?</a>
Similarly, in order to change the first letter of a paragraph to large, red text, you might use a pseudo-element rule like
 p:first-letter {color: red; font-size: xx-large;}
However, when you attempt to do this inline, you are forced to introduce an element to hold the first letter:
<p><span style=”color: red; font-size: xx-large;”>T</span>his is a test.</p>
While these examples indicate why these selectors were given the names pseudo-class and pseudo-element, they don’t really show us how to use such inline styles.
<a href=””
style=”{text-decoration: none;}
:link {color: blue;}
:visited {color: red;}
:hover {color: red; text-decoration: underline;}
:active {color: red;}”>Inline Link Styles?</a>
To set the first letter on paragraphs, we would use:
<p style=”{text-indent: 1em;
text-align: justify;
line-height: 150%;}
:first-letter {color: red; font-size: xx-large;}”>
This is the set of <p></p>
The emerging specification even suggested the importation of style sheets directly inline:
<div id=”navbar” style=”@import url(navigationstyles.css);”>just an example</div>
While all these ideas are quite interesting, more than seven years after the working draft was authored, not a single browser supports this syntax at the time this edition is being completed. So, besides being too closely bound to tags, understand that unless this situation has changed by the time you read this edition, only using inline styles is going to limit your application of some of the more useful CSS selectors. (Reference McGrill CSS)
These were some methods for using CSS, there are many other methods for using CSS but includes above three parent methods.  So for more Stay tune for next blogs mean while keep doing your coding work with different examples.
Do more exercises and ping back your problems.

Let’s know about CSS Error Handling

Sorry writing this blog after very long time, Yet this is not my original I was reading about Error handling in google and find some important points, which are presented here, We know the use of syntactically correct markup is certainly not encouraged by permissive browser parsers that correct mistakes or guess intent when faced with malformed markup. The situation for CSS is a bit better, and the CSS 2.1 specification does describe what browsers should do in the case of various errors, but then again, making the assumption that browsers are not permissive and correctly implement all aspects of Web specifications is dangerous.
Unknown Properties
If an unknown property is encountered, a CSS-conforming user agent should ignore the declaration. Given
h1 {color: red; trouble: right-here;}
the property trouble would simply be ignored and the rule would simply set the color. It does not matter what the position of the bogus property declaration is, the result should be the same as long as the declaration is otherwise well formed.
h1 {trouble: right-here; color: red;}
The case is obviously different if the various separators are missing.
Malformed Rules
In the case where semicolons (;), colons (:), quotes (‘or”), or curly braces ( { } ) are misused, a browser should try to handle any unexpected characters and read the properties until a matching value can be found. As an example, consider the simple case of forgetting a semicolon:
h1 {color: red text-decoration: underline; font-style: italic;}
In this case, we should see the browser continue to parse the value of color as “red text decoration: underline” before it sees a closing semicolon. The font-style property that follows would then be used. Because the color property has an illegal value, it should be ignored.
Other cases are a bit more obvious. For example, here we see the colon missing in a style rule declaration:
h1 {color red; text-decoration: underline; font-style: italic;}
In this case, the color property is simply ignored and the text is underlined and italic.
The situation for quotes and braces is the same, with compliant browsers working to find a matching closing character for any open construct, potentially destroying anything in between. Consider this set of rules, where quite a large amount of style may be lost:
h1 {color: green; font-family: “Super Font;}
h2 {color: orange;}
h3 {color: blue; font-family: “Duper Font”;}
Be careful, though, because in this case you might assume that the rule closes off with a quote, but that may introduce more open construct errors later on in the style sheet.
Unclosed Structures and End of File :
A CSS browser should close all braces and quotes when it reaches the end of a style sheet. While quite permissive, this would suggest that
<style type=”text/css”>
h1 {color: green
should render properly, as the open rule would be closed automatically by the end of the style sheet. Open quotes would also be closed in a similar manner when the end of the style sheet is reached. Testing reveals this action is actually the case in browsers, but creating a syntactically correct style sheet is obviously far superior than understanding the expected failures of a conformant browser.
Illegal or Unknown Property Values
CSS-conforming browsers must ignore a declaration with an illegal value. For example,
h1 {font-size: microscopic; color: red;}
would simply not set the font-size value but h1 elements would be red. Usage of illegal characters can turn what would appear to be a correct value into an incorrect one. For example,
h1 {color: green;}
is incorrect not because green is an illegal color, but because it is not the same as the keyword green when it is quoted.
Do not assume that a CSS-compliant browser will fix such small oversights. For example, a browser given
h1 {color: green forest;}
should not use green but instead ignore the whole rule. Of course, what browser vendors actually do in the face of malformed Web documents varies.
Incorrect @ Keywords and Media Values:
When an @ media value or media type for a <style> tag is used, incorrect values should be ignored. For example, if you specify <style type=”text/css” media=”tri-corder”>, the browser is supposed to ignore the entire <style> block unless it understands such an odd type. Media types will be discussed in depth later, but for now understand that when faced with syntax problems, a CSS-compliant browser should simply ignore anything related to misunderstood values.
Ignoring Network Failures
When style sheets are linked rather than placed within the page, the browser must apply all
types it is able to fetch and simply ignore those it can’t. So if you had
<link rel=”stylesheet” href=”global.css” type=”text/css”>
<link rel=”stylesheet” href=”pagelevel.css” type=”text/css”>

and the first was fetched by the browser, but the second failed, it would simply apply the rules it had. Obviously, such transitory errors are hard to account for, but other considerations presented in this section should have been caught in the validation of markup and style, discussed next.

Let’s work with JavaScript Events

As we discussed in previous blog (Basics of  Events in JavaScript) about some event names, There are some many other events are in JavaScript ,
Some Events are used with Media Elements in HTML: 
  • ·         onabort
  • ·         oncanplay
  • ·         oncalplaythrough
  • ·         ondurationchange
  • ·         onended
  • ·         onerror
  • ·         onlodeddata
  • ·         onloadedmetadata
  • ·         onloadstart
  • ·         onpause
  • ·         onplay
  • ·         onplaying
  • ·         onprogress
  • ·         onratechange
  • ·         onreadystatechange
  • ·         onseeked
  • ·         onseeking
  • ·         onstalled
  • ·         onsuspended
  • ·         ontimeupdate
  • ·         onvalumechange
  • ·         onwaiting

Some Events which are very important for our Browser:
  • ·         onafterprint
  • ·         onbeforeprint
  • ·         onbeforeload
  • ·         onblur
  • ·         onerror
  • ·         onfocus
  • ·         onhaschange
  • ·         onload
  • ·         onmessage
  • ·         onoffline
  • ·         ononline
  • ·         onpagehide
  • ·         onpageshow
  • ·         onpopstate
  • ·         onredo
  • ·         onresize
  • ·         onstorage
  • ·         onundo
  • ·         onunload

So these are some important events which are used in JavaScript for making a webpage more interactive.
Now Let’s do some live work with these events, Yet we can’t discuss all events but some important event can be discussed.

onload   Event:  The online event triggers when a Website loads in a browser. This event is defined in the BODY element. Let’s write some HTML code

Here we have defined the onload event in the BODY element, which displays an alert box showing the text, Welcome to My World!, when a web page loads. The output for the above code will be:

So this was a little bit about the onload Event, do some more Exercise from yourself and put the problems.

onsubmit  Event:  The onsubmit event is used with the FORM element and triggered  when the form is submitted. Let’s create a form and understand the onsubmit event, HTML code :

The above code is for FORM, here we added some fields like Name, Phone, Address, Email id. Next we have defined the onsubmit event in the FORM element, which displays the some message.
After filling this form when we click on submit button then alert box appears and shows the Text message:

So these are the examples of JavaScript Events.

Note : Now do exercise from yourself and put the question in Comment.

Calling Function with Timer in JavaScript

In JavaScript timer is the most important feature, it allows us to execute JavaScript function after a specified period; thereby, making it possible to add a new dimensions, time, to our website. With the help of timer , we can run a command at the specified intervals, run loops repeatedly at a predefined time, and synchronize multiple events in a particular time span.

There are various methods for using it:

           1.      The setTimeout() method:  Executes code at a specified interval. Syntax for this : 
                                                           setTimeout(function, delayTime)
In the above syntax the setTimeout() method contains two parameters – function and delayTime. The function parameter specifies the method that the timer calls and the delayTime parameter specifies the number of milliseconds to wait before calling the method.

Example :Let’s try with an example, this method is useful when we want to delay the execution of a particular code.  Let’s write a code :

The setTimeout(“alert(‘Hi, Welcome! Ankur Here.’)”, 5000) method is used to create a timed alert box. The first parameter of the setTimeout() method is a string that contains a JavaScript statement, alert(‘Hi, Welcome! Ankur Here.’), and 2ndparameter , 5000 , specifies the time in milliseconds after which the first parameter will esecute.
So output of this code will be:

      2.      The clearTimeout() method:  Deactivates or cancels the timer that is set using the setTime() method.    Syntax for this :

in the above syntax , timer is a variable that is created using the setTimeout() method.
      3.      The setInterval() method : Executes a function after specified time interval. The syntax for this :
setInterval(function, intervalTime)

In above syntax the setInterval() is the method contains two parameters- function and intervalTime. The function parameters specifies the method to be called; whereas, the intervalTime parameter specifies the time interval between the function calls.
Example :Let’s try with an example, this method is used to execute the code after every specified time intervals.  Let’s write a code:

In given code the setInterval() method is used to create a timer that calls the alert() method repeatedly. In the setInterval() method, the first parameter is a string that contains a JavScript statement, alert(‘Sorry ! 1 seconds.’). The second parameter specifies the time in milliseconds, 1000, after which the first parameter is displayed.

So the Output of this code will be :

      4.      The clearInterval() method: Deactivates or cancels the timer that is set using the setInterval() method.     The syntax for this :
The preceding syntax deactivates the inner timer variable that is created using the setInterval() method.

So Enjoy and work with Timer in JavaScript.

Function in JavaScript

All of us know function is a collection of statements that is executed when it is called at some point in a program. A function performs a specific task within a program independent of the rest code in the program. We can call the function from anywhere within a program. We can also define the parameters to be passed with function while calling the function. The parameters in a function are used to exchange information between a calling statement and function. We can define a function by using the function keyword.
Syntax for a function :

Above syntax has name of function, and parameters of a function.

JavaScript functions are divided into two categories:

Function without Parameters: Does not contain parameters. This code written in these function is static, implying that the values of members of these function cannot be changed at runtime.
Function with parameters:  Contains parameter in its parenthesis, such as integer and string. Unlike function without parameters, the values of members of these function can be changed at run time by passing different values of their parameters.

Now let’s understand the JavaScript function using a simple example:

We have created a function named simple under the head section.

The simple() function an alert message with Thank you.

The onload event handler under the BODY element calls simple() function when the document is loaded in the browser.
Output :

Selection Statements in JavaScript

Suppose there is  a web page in our shopping website, which accepts a price range from the users. When the users provide a price range, the items or products that lie within the specified price range displayed. Such functionality and logic can be incorporated by using selection statement in the script.
Selection statement use a condition to selector determine the statement that are to be executed. These statements help us to make decisions and change the flow of execution of the statements. In the JavaScript, there are three selection statements :
  1.         If
  2.       .  If….else
  3.      .   Switch

Let’s know more about these statements:

The if Statement : The if statement is one of the most basic and simplest control flow statement. We can use the if statement when we want to execute a group of one or more script statements only when a particular condition is met.
Syntax :
              Statement 1
In the preceding syntax, if JavaScript keyword that signifies an if statement and contain a condition, which need to be evaluated to true, then the script statement, represented by statement 1, enclosed within the curly braces is executed. If the condition evaluates to false, then the statement enclosed within the curly braces skipped and the statement immediately after closing curly brace(}) is executed.

Let’s Understand :  A simple example for If Statement is given below:

                                <TITLE>Using if Statement</TITLE>
                                <H1>Using the if Statement in the script </H1>
                                <SCRIPT type=”text/javascript”>
                                                var Number=45;
                                                if((Number%2) != 0)
                                                                document.write(Number + ” is an odd number”);
                                                document.write(“<BR/>Thank you!”);

The if…..else statement:As we know the if statement allows us to execute a set of statements only when a particular condition is true. However, if we want to execute another set of statements when the condition is false, then we can use the if….else statement.
            Statement 1
Statement  2
In the given syntax, if and else keywords that signify the if…else statement. The condition of the if….else statement if enclosed within parentheses. If the condition is true, then the group of statements represented by statement 1 enclosed within the first curly braces is executed. If the condition is false, then the statement 1 is skipped and the group of statements, represented by statement 2 of the else block is executed.

Let’s Try: A simple if else Statement is given below :

                                <TITLE>if…else Statement</TITLE>
                                <H1>Using the if…else Statement in the Script</H1>
                                <SCRIPT type=”text/javascript”>
                                                var Number=44;
                                                if((Number%2) != 0)
                                                                document.write(Number + ” is an odd number”);
                                                                document.write(Number + ” is an even  number”);
                                                document.write(“<BR/>Thank you!”);
Out Put :

The switch statement:A switch statement is used to select a particular group of statements to be executed among several other groups of statements. The group of statements that is to be executed is selected on the basis of a numeric or string expression.
case value1:statement 1
case value2:statement 2
case value3: statement 3
In given syntax, switch case, and break are JavaScript keywords. The switch keyword indicates the switch statement. In a switch statement the expression that is to be evaluated is specified within parentheses. This expression is checked against each of the case values specified in the case statements. If any of the case values match the value of the expression, the group of statement (statement 1, statement 2 or statement 3) specified in the respective case statement is executed. If none of the case values matches the value of the expression, then the default statement, specified by the default keyword, is executed. The default statement is generally placed at the end of the switch statement; however, we can place it anywhere within the switch statement.

   Let’s Try: A simple example for Switch statement is given below :

                                <TITLE>Using switch Statement</TITLE>
                                <H1>Using switch Statement in the script</H1>
                                <SCRIPT type=”text/javascript”>
                                                var letter=”I”;
                                                                case “A”:document.write(“A is a vowel”);
                                                                case “E”:document.write(“E is a vowel”);
                                                                case “I”:document.write(“I is a vowel”);
                                                                case “O”:document.write(“O is a vowel”);
                                                                case “U”:document.write(“U is a vowel”);
                                                document.write(“<BR/>Thank You!”);