CSS – Cursors

Tags

The cursor property is supported in all major browsers.

One good usage of this property is in using images for submit buttons on forms.

By default, when a cursor hovers over a link, the cursor changed from a pointer to a hand. For a submit button on a form this does not happen.

Therefore, using the cursor property to change the cursor to a hand whenever someone hovers over an image that is a submit button. This provides a visual clue that they can click it.

The table that follows shows possible values for the cursor property:

Value

Description

auto Shape of the cursor depends on the context area it is over. For example an I over text, a hand over a link, and so on…
crosshair A crosshair or plus sign
default An arrow
pointer A pointing hand (in IE 4 this value is hand)
move The I bar
e-resize The cursor indicates that an edge of a box is to be moved right (east)
ne-resize The cursor indicates that an edge of a box is to be moved up and right (north/east)
nw-resize The cursor indicates that an edge of a box is to be moved up and left (north/west)
n-resize The cursor indicates that an edge of a box is to be moved up (north)
se-resize The cursor indicates that an edge of a box is to be moved down and right (south/east)
sw-resize The cursor indicates that an edge of a box is to be moved down and left (south/west)
s-resize The cursor indicates that an edge of a box is to be moved down (south)
w-resize The cursor indicates that an edge of a box is to be moved left (west)
text The I bar
wait An hour glass
help A question mark or balloon, ideal for use over help buttons
<url> The source of a cursor image file
<p>Move the mouse over the words to see the cursor change:</p><div style=”cursor:auto”>Auto</div><div style=”cursor:crosshair”>Crosshair</div>

<div style=”cursor:default”>Default</div>

<div style=”cursor:pointer”>Pointer</div>

<div style=”cursor:move”>Move</div>

<div style=”cursor:e-resize”>e-resize</div>

<div style=”cursor:ne-resize”>ne-resize</div>

<div style=”cursor:nw-resize”>nw-resize</div>

<div style=”cursor:n-resize”>n-resize</div>

<div style=”cursor:se-resize”>se-resize</div>

<div style=”cursor:sw-resize”>sw-resize</div>

<div style=”cursor:s-resize”>s-resize</div>

<div style=”cursor:w-resize”>w-resize</div>

<div style=”cursor:text”>text</div>

<div style=”cursor:wait”>wait</div>

<div style=”cursor:help”>help</div>

Thanks,

Advertisements

Inroduction to HTML5

Tags

What Is HTML5?

HTML5 is the newest hypertext markup language for websites from the World Wide Web Consortium (W3C). The first draft was made public in 2008, but not much happened until 2011. In 2011, HTML5 was released and people started writing about it and using it, but the support in different browsers was still poor. Today all major browsers (Chrome, Safari, Firefox, Opera, IE) offer HTML5 support, therefore the newest HTML technology can be used at its best today.

HTML5 works with CSS3 and is still in development. W3C plans to release a stable version next year, but it still looks like this is a long shot. Since its release, HTML5 has been in continuous development, with the W3C adding more and more impressive features, therefore it seems quite unlikely that HTML5′s development will end soon, which is not necessarily a bad thing.

HTML5 is the successor of HTML 4.01, released for the first time in 1999. The internet has changed significantly since 1999 and it seemed like the creation of HTML5 was necessary. The new markup language was developed based on pre-set standards:

  • New features should be based on HTML, CSS, DOM, and JavaScript.
  • The need for external plugins (like Flash) needs to be reduced.
  • Error handling should be easier than in previous versions.
  • Scripting has to be replaced by more markup.
  • HTML5 should be device-independent.
  • The development process should be visible to the public.
  • Less dependence on plugins for functionality.
  • Scripting should be replaced with markup whenever possible.
  • Device independence (i.e., available on all devices and providing the same end experience).
  • Public development process so people can see what’s going on.

What’s new?

HTML5 was created to make the coding process easier and more logical. You will see a bit later that many syntaxes are now deprecated and soon to be kicked out through the back door. The unique and impressive features HTML5 comes with are in the multimedia department. Many of the features it comes with have been created with the consideration that users should be able to run heavy content on low-powered devices. The syntactic features include the new <video>, <audio> and <canvas> elements, but also integration of vector graphics content (what we knew before as being the <object> tags). This means that multimedia and graphic content on the web will be handled and executed easier and faster, without the need of plugins or APIs.

There are a bunch load of new syntaxes added, but below I will name and describe the most important. The rest of them can always be found in W3C’s HTML5 section.

  • <article> – this tag defines an article, a user comment or a post, so an independent item of content
  • <aside> – the aside tag marks content aside from the page content, which for example could be a lateral sidebar
  • <header><footer> – you won’t need to manually name IDs for headers and footers, as now you have a pre-defined tag for them
  • <nav> – the navigation can now be placed in the markup in between the nav tags, which will automatically make your lists act like navigation
  • <section> – this is another important new syntax, as it can define any kind of sections in your document. It works pretty much like a div which separates different sections.
  • <audio><video> – these two obviously mark sound or video content, which will now be easier to run by devices.
  •  – this new tag defines a container for interactive content (plugin) or external application
  • <canvas> – the canvas tag is quite exciting, as it allows drawing graphics via scripting (mostly JavaScript, but some others can be employed as well)
  • HTML5 also deprecates some tags: <acronym>, <applet>, <font>, <frame>, <frameset>,<noframes>, and a handful of others.

HTML4 has worked well, but it obviously has a number of flaws. The team behind HTML5 has a certain high-level plan for the next step in HTML, which means that HTML5 must be built on the following principles:

What is important to remember is that the new HTML5 tags do not always work as the ones before. For example, the header and footer tags will not only mark the start and the end of a page, but also the start and the end of each section you have. This means that these two tags are likely to be used more than once in the whole page. In the illustration below can you see what I mean.

Oh yes, and the DOCTYPE declaration finally makes some sense. Or, at least, this time it is much simpler than before and it is very easy for us to remember and we won’t have to search for it on the web or copy it from site to site. <!DOCTYPE html> closed by </html> at the end of the page is something we waited for for a long time to come and now it finally is here.

Moreover, complex XHTML declarations many of us used before can now be replaced with <html lang=”en”> and long encoding declarations can simply be written in this way: <meta charset=”utf-8″>. Can it get simpler than that? It most definitely can’t.

The following tags from HTML 4.01 are now removed from HTML5, therefore browsers do not offer support for them anymore. This means that it is a good idea to go back to your HTML pages and check for them, as they might disrupt the design in the latest browsers.

  • <acronym>
  • <applet>
  • <basefont>
  • <big>
  • <center>
  • <dir>
  • <font>
  • <frame>
  • <frameset>
  • <noframes>
  • <strike>
  • <tt>

Things to know about HTML5

It is crucial to remember that HTML5 is built on the success of its previous version, HTML 4.01, which is undoubtedly the best version ever. In order to be better at using HTML5 you do not need to forget everything about the previous version. You are not learning a totally new language here. Keep your beloved syntaxes and keep the way you used to format your code, only remember that now you need to build upon the coding skills you already have.

In case you have absolutely no knowledge of HTML and you want to start now, I advise you to start with HTML 4.01 and only when you master it move onto HTML5. Starting with the latest version is like learning to run before learning to walk – which is impossible as far as I know. HTML 4.01 still contains the basics of HTML5, therefore in my opinion you should have strong knowledge of former HTML versions in order to be able to master HTML5.

The upside of learning HTML5 now is that the new markup language works right away. You can basically do whatever you want with it today – and it is supported in all major browsers. From video to geolocation, local storage and microdata annotations, HTML5 is something we need to start using. If you are in the design business, sticking with HTML 4.01 is a mistake, because everybody will move on while you will remain behind.

HTML5 is definitely here to stay. It is created to sustain today’s necessities and especially because it is in continuous development, it will be able to sustain the changes that will happen in the industry for quite some time. One of the reasons behind HTML5 taking so much time to develop is because the W3C had to analyze lots of factors and think of the future. They took their time and finally delivered something that can easily be labelled as a high-quality product.

Quick Reference…

What is the status of the development of the HTML 5 standard?
HTML5 is being developed as the next major revision of HTML (HyperText Markup Language), the core markup language of the World Wide Web. The Web Hypertext Application Technology Working Group (WHATWG) started work on the specification in June 2004 under the name Web Applications 1.0. As of March 2010, the specification is in the Draft Standard state at the WHATWG, and in Working Draft state at the W3C.
 
What are the new APIs provided by the HTML 5 standard? Give a brief description of each
·         The canvas element: Canvas consists of a drawable region defined in HTML code with height and width attributes. JavaScript code may access the area through a full set of drawing functions similar to other common 2D APIs, thus allowing for dynamically generated graphics. Some anticipated uses of the canvas include building graphs, animations, games, and image composition.
·         Timed media playback
·         Offline storage database
·         Document editing
·         Drag-and-drop
·         Cross-document messaging
·         Browser history management
·         MIME type and protocol handler registration
 
What is the purpose of HTML5 versus XHTML?

HTML5 is the next version of HTML 4.01, XHTML 1.0 and DOM Level 2 HTML. It aims to reduce the need for proprietary plug-in-based rich internet application (RIA) technologies such as Adobe Flash, Microsoft Silverlight, Apache Pivot, and Sun JavaFX. Instead of using those plugins, it enables browser to serve elements such as video and audio without any additional requirements on the client machine.

What is the difference between HTML and HTML5 ?

HTML5 is nothing more than upgraded version of HTML where in HTML5 supports the innovative features such as Video, Audio/mp3, date select function , placeholder , Canvas, 2D/3D Graphics, Local SQL Database added so that no need to do external plugin like Flash player or other library elemenents.

WHAT are some other advantages of HTML5?

a)      Cleaner markup than earlier versions of HTML

b)      Additional semantics of new elements like <header>, <nav>, and <time>

c)       New form input types and attributes that will (and in Opera’s case, do) take the hassle out of scripting forms.

What is the use of Canvas Element in HTML5?

HTML5 Canvas element can be used to draw graphics images on a web page by using javascript.

What is the  <!DOCTYPE>? Is it mandatory to use in HTML5?

The <!DOCTYPE> is an instruction to the web browser about what version of HTML the page is written in. The <!DOCTYPE> tag does not have an end tag. It is not case sensitive.The <!DOCTYPE> declaration must be the very first thing in HTML5 document, before the <html> tag.  As In HTML 4.01, all <! DOCTYPE > declarations require a reference to a Document Type Definition (DTD), because HTML 4.01 was based on Standard Generalized Markup Language (SGML). WHERE AS HTML5 is not based on SGML, and therefore does not require a reference to a Document Type Definition (DTD).

What are the New Media Elements in HTML5?

New Media Elements in HTML5 are :

TAG DESCRIPTION
<audio> For multimedia content, sounds, music or other audio streams
<video> For video content, such as a movie clip or other video streams
<source> For media resources for media elements, defined inside video or audio
elements
For embedded content, such as a plug-in
<track> For text tracks used in mediaplayers

 

What is the major improvement with HTML5 in reference to Flash?

Flash is not supported by major mobile devices such as iPad, iPhone and universal android applications. Those mobile devices have lack of support for installing flash plugins. HTML5 is supported by all the devices, apps and browser including Apple and Android products. Compared to Flash, HTML5 is very secured and protected. That eliminates major concerns that we have seen with Flash.

What is the use of localStorage in HTML5 ?

Before HTML5 LocalStores was done with cookies. Cookies are not very good for large amounts of data, because they are passed on by every request to the server, so it was very slow and in-effective.

In HTML5, the data is NOT passed on by every server request, but used ONLY when asked for. It is possible to store large amounts of data without affecting the website’s performance.and The data is stored in different areas for different websites, and a website can only access data stored by itself.

And for creating localstores just need to call localStorage object like below we are storing name and address

<script type=”text/javascript”>

localStorage.name=”PCDS”;

document.write(localStorage.name);

</script>

<script type=”text/javascript”>

localStorage.address=”Mumbai India..”;

document.write(localStorage.address);

</script>

What is the sessionStorage Object in html5 ? How to create and access ?

 

The sessionStorage object stores the data for one session. The data is deleted when the user closes the browser window. like below we can create and access a sessionStorage here we created “name” as session

<script type=”text/javascript”>

sessionStorage.name=”PCDS”;

document.write(sessionStorage.name);

</script>

What are the new APISs provided by the HTML5 standard ,give a brief description of each ?

 

The canvas element: Canvas consists of a drawable region defined in HTML code with height and width attributes. JavaScript code may access the area through a full set of drawing functions similar to other common 2D APIs, thus allowing for dynamically generated graphics. Some anticipated uses of the canvas include building graphs, animations, games, and image composition.

• Timed media playback
• Offline storage database
• Document editing
• Drag-and-drop
• Cross-document messaging
• Browser history management
• MIME type and protocol handler registration

 

What elements have disappeared?

As mentioned above, <frame> and <frameset> have been eliminated. Other elements that are no longer supported include: <noframe>, <applet>, <bigcenter> and <basefront>.

What is the difference between SVG and <Canvas>?

 

<Canvas> is an element that manipulates two-dimensional (2D) pixels while Scalable Vector Graphics works in 2D and three-dimensional (3D) vectors. Essentially, <Canvas> is to SVG as Photoshop is to Illustrator.

What is the difference between HTML5 interaction in Sencha and Twitter/Bootstrap?

Sencha and Twitter/Bootstrap are both HTML development frameworks that integrate HTML5, CSS3, and JavaScript. The major difference is that in Sencha, the three languages are all comingled together in code, whereas in Bootstrap, HTML and CSS and decoupled.

What purpose do Work Workers serve and what are some of their benefits?

Web Workers are background scripts that do not interfere with the user interface or user interactions on a webpage, allowing HTML to render uninterrupted while JavaScript works in the background.

Describe the difference between cookies, sessionStorage, andlocalStorage.

 

Cookies are small text files that websites place in a browser for tracking or login purposes. Meanwhile, localStorage and sessionStorage are new objects, both of which are storage specifications but vary in scope and duration. Of the two, localStorage is permanent and website-specific whereas sessionStorage only lasts as long as the duration of the longest open tab.

What is the difference in caching between HTML5 and the old HTML?

An important feature of HTML5 is the Application Cache. It creates an offline version of a web application. and stores website files such as HTML files, CSS, images, and JavaScript, locally. It is a feature that speeds up site performance

-Thanks,

Good example for JSONP

Tags

,

  <!DOCTYPE html>
  <html>
  <title>JSONP</title>
  <head>
  <script src=”http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js“>
  </script>
  <script>
  $(document).ready(function(){
  $(‘#idSubmit’).click(function() {
  displayTagImages($(‘#idText’).val());
  });
  });
   
  function displayTagImages(data) {
  var txtVal = data;
  $(‘#idText’).val(data);
  $(‘#image-container’).html(“”);
  $.ajax({
  type : ‘GET’,
  url : “http://api.flickr.com/services/feeds/photos_public.gne?tags=&#8221; + txtVal,
  data : “&lang=en-us&format=json&jsoncallback=?”,
  success : function(data) {
   
  $.each(data.items, function(i, item) {
   
  if (item.media.m) {
  var container = $(“<div/>”);
  var tagImgs = $(“<img/>”).attr(“src”, item.media.m).appendTo(container);
  var imgTitle = $(“<p/>”).html(‘<b>Title</b> : ‘ + item.title).appendTo(container)
  var imgTags = $(“<p/>”).html(‘<b>Tags</b> :’).appendTo(container);
  var imgTags1 = item.tags;
  var imgTags1 = imgTags1.split(‘ ‘);
  $.each(imgTags1, function(index, value) {
   
  var txt = imgTags1[index] ;
  $(‘<span style=”padding-left:4px;”/>’).html($(“<a>” + imgTags1[index] + “</a>”).attr(“href”, imgTags1[index])).appendTo(
  container).click(function(data) {
  displayTagImages(txt);
  return false;
  });
   
  });
  $(“#image-container”).append(container);
  if (i == 9)
  return false;
  }
  });
  },
  dataType : ‘jsonp’
  });
  }
  </script>
  </head>
  <body>
  <div id=”images”></div>
  <b>Enter Tag Name :</b> <input type=”text” name=”” id=”idText” value=”peacock”></input>
  <input type=”submit” id=”idSubmit” value=”Submit”></input>
  <div id=”image-container”></div>
  <span></span>
  </body>
  </html>
 

Meta Tags

Tags

,

The HTML <meta> Element

  • Metadata is data (information) about data.
  • The <meta> tag provides metadata about the HTML document. Metadata will not be displayed on the page, but will be machine parsable.
  • Meta elements are typically used to specify page description, keywords, author of the document, last modified, and other metadata.
  • The metadata can be used by browsers (how to display content or reload page), search engines (keywords), or other web services.

<meta> tags always go inside the <head> element.

<meta> Tags – Examples of Use

<head>
<meta name=”description” content=”Free Web tutorials”>
<meta name=”keywords” content=”HTML,CSS,XML,JavaScript”>
<meta name=”author” content=”Hege Refsnes”>
<meta charset=”UTF-8″>
</head>

Definition and Usage

Metadata is data (information) about data.

The <meta> tag provides metadata about the HTML document. Metadata will not be displayed on the page, but will be machine parsable.

Meta elements are typically used to specify page description, keywords, author of the document, last modified, and other metadata.

The metadata can be used by browsers (how to display content or reload page), search engines (keywords), or other web services.

Note: <meta> tags always goes inside the <head> element.

Note: Metadata is always passed as name/value pairs.

Note: The content attribute MUST be defined if the name or the http-equiv attribute is defined. if none of these are defined, the content attribute CANNOT be defined.


Differences Between HTML 4.01 and HTML5

The scheme attribute is not supported in HTML5.

HTML5 has a new attribute, charset, which makes it easier to define charset:

  • HTML 4.01: <meta http-equiv=”content-type” content=”text/html; charset=UTF-8″>
  • HTML5: <meta charset=”UTF-8″>

Differences Between HTML and XHTML

In HTML the <meta> tag has no end tag.

In XHTML the <meta> tag must be properly closed.

Define keywords for search engines:

<meta name=”keywords” content=”HTML, CSS, XML, XHTML, JavaScript”>

Define a description of your web page:

<meta name=”description” content=”Free Web tutorials on HTML and CSS”>

Define the author of a page:

<meta name=”author” content=”Hege Refsnes”>

Refresh document every 30 seconds:

<meta http-equiv=”refresh” content=”30″>

 

<meta http-equiv=”X-UA-Compatible” content=”IE=Edge,chrome=1″>

Example for setAttribute : 

 

<meta id=”description” name=”description”

content=”example meta description content” />

<meta name=”keywords” content=”example meta keywords content” />

<meta name=”author” content=”example author conent” />

<title>example title content</title>

<script type=”text/javascript”>

 window.onload = function () {

     setProductMeta();

 }

function setProductMeta(){

 document.getElementById(“description”).setAttribute(“content”,”dynamic meta description”);

 document.getElementById(“keywords”).setAttribute(“content”,”dynamic meta description”);

 document.title = ‘dynamic meta title’;

}

</script>

Example for getAttribute : 

 

<meta id=”description” name=”description”

content=”example meta description content” />

<meta name=”keywords” content=”example meta keywords content” />

<meta name=”author” content=”example author conent” />

<script type=”text/javascript”>

window.onload = function () {

 setProductMeta();

}

function setProductMeta(){

 var metaDesc = document.getElementById(“description”).getAttribute(“content”);

 var metaKeys = document.getElementById(“keywords”).getAttribute(“content”);

 var metaAuthor = document.getElementById(“author”).getAttribute(“content”);

 document.getElementById(“demoDesc”).innerHTML= metaDesc;

 document.getElementById(“demoKeys”).innerHTML= metaKeys;

 document.getElementById(“demoAuthor”).innerHTML= metaAuthor;

}

</script>

<div id=”demoDesc”></div>

<div id=”demoKeys”></div>

<div id=”demoAuthor”></div>

 

<meta http-equiv=”X-UA-Compatible” content=”IE=Edge,chrome=1″>

jQuery:

$(‘head’).append(‘<meta http-equiv=”X-UA-Compatible” content=” IE=Edge,chrome=1″ /> ‘);

JavaScript:

document.getElementsByTagName(‘head’)[0].innerHTML += ‘<meta id=”viewport” name=”viewport” content=”width=320; initial-scale=1.0; maximum-scale=1.0; user-scalable=0;”>’;

<script>

var meta = document.createElement(‘meta’);

meta.setAttribute(‘http-equiv’, ‘X-UA-Compatible’);

meta.setAttribute(‘content’, ‘IE=Edge’);

document.getElementsByTagName(‘head’)[0].appendChild(meta);

</script>

 Thanks,

jQuery PPT’s

Tags

,

Here is JQUERY PPT

jQuery_PPT’s

Here we cover the following topics.

    • About jQuery
      • Introduction to jquery
      • Differences between javascript and jquery
      • Cross browser compatibility
      • Selectors,Events,Effects,Utilities,Filters and Etc.
    • Plugins
      • Plugin types
      • Plugin examples
      • Preparation of plugins
    • jQuery AJAX
    • jQuery UI
      • Interactions
      • Widgets
      • Effects
      • Themes
    • Common jQuery mistakes
    • Samples and Demos.

Good Luck…!!!

HTML5 form elements

Tags

IE10 includes support for HTML5 Forms. HTML5 Forms offers two major advantages over previous versions: new input types and built in validation.

The new HTML5 input types are:

color ,date,  datetime,  datetime-localemailmonthnumberrangesearchtel,   timeurl ,week

Introducing New Input Types

The current draft of the HTML5 specification brings with it 13 new input field types. Yes, thirteenbrand-new, shiny ways of defining the good old input element, so make some room beside textinputs for the following:

  • email for email addresses, perfect to use immediately
  • tel for telephone numbers (some browsers may strip whitespace), fine for immediate use
  • url for web addresses, good to use now
  • color for hexadecimal color values; here’s hoping we see OS-native color pickers in the future!
  • number for whole numbers; some browsers provide up/down arrows next to the input field. You can also limit the number to a given range with the min and max attributes.
  • range for a numeric input with a slider widget; like the number input type, you can use min and max attributes to define the range. You can also use the step attribute to control the increments in which the slider moves. This is ready for use, as browsers that don’t support it will simply display a text field—but be careful how you use this one. Regardless of how cool they may look, sliders are only good for certain tasks (such as price ranges); in most cases, a regular number field will be easier for your users.
  • search for search keywords, so naturally just the tool for site searches. Be wary of the current Mac OS rendering: it looks just like the built-in Spotlight search, but there’s no overriding the styles if you need to display it differently.
  • datemonthweektimedatetime, and datetime-local for date-related inputs. Several exciting new fields—now we just have to wait for all the browsers to implement it.

HTML5 form attributes

Read more :  http://www.the-art-of-web.com/html/html5-form-validation/#.UlOhA9KnqBc

Example  : http://ie.microsoft.com/testdrive/HTML5/Forms/

Good Luck…

Test your jQuery skill..!!!

Tags

,

Q1. What is jQuery?
Ans: jQuery is fast, lightweight and feature-rich client side JavaScript Library/Framework which helps in to traverse HTML DOM, make animations, add Ajax interaction, manipulate the page content, change the style and provide cool UI effect. It is one of the most popular client side library and as per a survey it runs on every second website.

Q2. Why do we use jQuery?
Ans: Due to following advantages.

  • Easy to use and learn.
  • Easily expandable.
  • Cross-browser support (IE 6.0+, FF 1.5+, Safari 2.0+, Opera 9.0+)
  • Easy to use for DOM manipulation and traversal.
  • Large pool of built in methods.
  • AJAX Capabilities.
  • Methods for changing or applying CSS, creating animations.
  • Event detection and handling.
  • Tons of plug-ins for all kind of needs.

Q3. How JavaScript and jQuery are different?
Ans: JavaScript is a language While jQuery is a library built in the JavaScript language that helps to use the JavaScript language.

Q4. Is jQuery replacement of Java Script?
Ans: No. jQuery is not a replacement of JavaScript. jQuery is a different library which is written on top of JavaScript. jQuery is a lightweight JavaScript library that emphasizes interaction between JavaScript and HTML.

Q5. Is jQuery a library for client scripting or server scripting?
Ans. Client side scripting.

Q6. Does jQuery follow W3C recommendations?
Ans: No.

Q7. What is the basic need to start with jQuery?
Ans: To start with jQuery, one need to make reference of it’s library. The latest version of jQuery can be downloaded from jQuery.com.

Q8. Which is the starting point of code execution in jQuery?
Ans: The starting point of jQuery code execution is $(document).ready() function which is executed when DOM is loaded.

Q9. What does dollar sign ($) means in jQuery?
Ans: Dollar Sign is nothing but it’s an alias for JQuery. Take a look at below jQuery code.

1 $(document).ready(function(){
2 });

Over here $ sign can be replaced with “jQuery” keyword.

1 jQuery(document).ready(function(){
2 });

Q10. Can we have multiple document.ready() function on the same page?
Ans: YES. We can have any number of document.ready() function on the same page.

Q11. Can we use our own specific character in the place of $ sign in jQuery?
Ans: Yes. It is possible using jQuery.noConflict().

Q12. Is it possible to use other client side libraries like MooTools, Prototype along with jQuery?
Ans: Yes.

Q13. What is jQuery.noConflict?
Ans: As other client side libraries like MooTools, Prototype can be used with jQuery and they also use $() as their global function and to define variables. This situation creates conflict as $() is used by jQuery and other library as their global function. To overcome from such situations, jQuery has introduced jQuery.noConflict().

1 jQuery.noConflict();
2 // Use jQuery via jQuery(…)
3 jQuery(document).ready(function(){
4    jQuery(“div”).hide();
5 });

You can also use your own specific character in the place of $ sign in jQuery.

1 var $j = jQuery.noConflict();
2 // Use jQuery via jQuery(…)
3 $j(document).ready(function(){
4    $j(“div”).hide();
5 });

Q14. Is there any difference between body onload() and document.ready() function?
Ans: document.ready() function is different from body onload() function for 2 reasons.

  1. We can have more than one document.ready() function in a page where we can have only one body onload function.
  2. document.ready() function is called as soon as DOM is loaded where body.onload() function is called when everything gets loaded on the page that includes DOM, images and all associated resources of the page.

Q15. What is the difference between .js and .min.js?
Ans: jQuery library comes in 2 different versions Production and Deployment. The deployment version is also known as minified version. So .min.js is basically the minified version of jQuery library file. Both the files are same as far as functionality is concerned. but .min.js is quite small in size so it loads quickly and saves bandwidth.

Q16. Why there are two different version of jQuery library?
Ans: jQuery library comes in 2 different versions.

  1. Production
  2. Deployment

The production version is quite useful at development time as jQuery is open source and if you want to change something then you can make those changes in production version. But the deployment version is minified version or compressed version so it is impossible to make changes in it. Because it is compressed, so its size is very less than the production version which affects the page load time.

Q17. What is a CDN?
Ans: A content delivery network or content distribution network (CDN) is a large distributed system of servers deployed in multiple data centers across the Internet. The goal of a CDN is to serve content to end-users with high availability and high performance.

Q18. Which are the popular jQuery CDN? and what is the advantage of using CDN?
Ans: There are 3 popular jQuery CDNs.

  1. 1. Google.
  2. 2. Microsoft
  3. 3. jQuery.

Advantage of using CDN.

  • It reduces the load from your server.
  • It saves bandwidth. jQuery framework will load faster from these CDN.
  • The most important benefit is it will be cached, if the user has visited any site which is using jQuery framework from any of these CDN

Q19. How to load jQuery from CDN?
Ans: Below is the code to load jQuery from all 3 CDNs.
Code to load jQuery Framework from Google CDN

1 <script type=”text/javascript”
2     src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js“>
3 </script>

Code to load jQuery Framework from Microsoft CDN

1 <script type=”text/javascript”
2     src=”http://ajax.microsoft.com/ajax/jquery/jquery-1.9.1.min.js“>
3 </script>

Code to load jQuery Framework from jQuery Site(EdgeCast CDN)

1 <script type=”text/javascript”
2     src=”http://code.jquery.com/jquery-1.9.1.min.js“>
3 </script>

Q20. How to load jQuery locally when CDN fails?
Ans: It is a good approach to always use CDN but sometimes what if the CDN is down (rare possibility though) but you never know in this world as anything can happen.

Below given jQuery code checks whether jQuery is loaded from Google CDN or not, if not then it references the jQuery.js file from your folder.

1 <script type=”text/javascript”src=”http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js“></script>
2 <script type=”text/javascript”>
3 if (typeof jQuery == ‘undefined’)
4 {
5   document.write(unescape(“%3Cscript src=’Scripts/jquery.1.9.1.min.js’ type=’text/javascript’%3E%3C/script%3E”));
6 }
7 </script>

It first loads the jQuery from Google CDN and then check the jQuery object. If jQuery is not loaded successfully then it will references the jQuery.js file from hard drive location. In this example, the jQuery.js is loaded from Scripts folder.

Q21. What are selectors in jQuery and how many types of selectors are there?
Ans: To work with an element on the web page, first we need to find them. To find the html element in jQuery we use selectors. There are many types of selectors but basic selectors are:

  • Name: Selects all elements which match with the given element Name.
  • #ID: Selects a single element which matches with the given ID
  • .Class: Selects all elements which match with the given Class.
  • Universal (*): Selects all elements available in a DOM.
  • Multiple Elements E, F, G: Selects the combined results of all the specified selectors E, F or G.
  • Attribute Selector: Select elements based on its attribute value.

Q22. How do you select element by ID in jQuery?
Ans: To select element use ID selector. We need to prefix the id with “#” (hash symbol). For example, to select element with ID “txtName”, then syntax would be,

1 $(‘#txtName’)

Q23. What does $(“div”) will select?
Ans: This will select all the div elements on page.

Q24. How to select element having a particular class (“.selected”)?
Ans: $(‘.selected’). This selector is known as class selector. We need to prefix the class name with “.” (dot).

Q25. What does $(“div.parent”) will select?
Ans: All the div element with parent class.

Q26. What are the fastest selectors in jQuery?
Ans: ID and element selectors are the fastest selectors in jQuery.

Q27. What are the slow selectors in jQuery?
Ans: class selectors are the slow compare to ID and element.

Q28. How jQuery selectors are executed?
Ans: Your last selectors is always executed first. For example, in below jQuery code, jQuery will first find all the elements with class “.myCssClass” and after that it will reject all the other elements which are not in “p#elmID”.

1 $(“p#elmID .myCssClass”);

Q29. Which is fast document.getElementByID(‘txtName’) or $(‘#txtName’).?
Ans: Native JavaScipt is always fast. jQuery method to select txtName “$(‘#txtName’)” will internally makes a call to document.getElementByID(‘txtName’). As jQuery is written on top of JavaScript and it internally uses JavaScript only So JavaScript is always fast.

Q30. Difference between $(this) and ‘this’ in jQuery?
Ans: this and $(this) refers to the same element. The only difference is the way they are used. ‘this’ is used in traditional sense, when ‘this’ is wrapped in $() then it becomes a jQuery object and you are able to use the power of jQuery.

1 $(document).ready(function(){
2     $(‘#spnValue’).mouseover(function(){
3        alert($(this).text());
4   });
5 });

In below example, this is an object but since it is not wrapped in $(), we can’t use jQuery method and use the native JavaScript to get the value of span element.

1 $(document).ready(function(){
2     $(‘#spnValue’).mouseover(function(){
3        alert(this.innerText);
4   });
5 });

Q31. How do you check if an element is empty?
Ans: There are 2 ways to check if element is empty or not. We can check using “:empty” selector.

1 $(document).ready(function(){
2     if ($(‘#element’).is(‘:empty’)){
3        //Element is empty
4   }
5 });

And the second way is using the “$.trim()” method.

1 $(document).ready(function(){
2      if($.trim($(‘#element’).html())==”) {
3        //Element is empty
4   }
5 });

Q32. How do you check if an element exists or not in jQuery?
Ans: Using jQuery length property, we can ensure whether element exists or not.

1 $(document).ready(function(){
2     if ($(‘#element’).length > 0){
3        //Element exists
4   });
5 });

Q33. What is the use of jquery .each() function?
Ans: The $.each() function is used to iterate over a jQuery object. The $.each() function can be used to iterate over any collection, whether it is an object or an array.

Q34. What is the difference between jquery.size() and jquery.length?
Ans: jQuery .size() method returns number of element in the object. But it is not preferred to use the size() method as jQuery provide .length property and which does the same thing. But the .length property is preferred because it does not have the overhead of a function call.

Q35. What is the difference between $(‘div’) and $(‘<div/>’) in jQuery?
Ans: $(‘<div/>’) : This creates a new div element. However this is not added to DOM tree unless you don’t append it to any DOM element.

$(‘div’) : This selects all the div element present on the page.

Q36. What is the difference between parent() and parents() methods in jQuery?
Ans: The basic difference is the parent() function travels only one level in the DOM tree, where parents() function search through the whole DOM tree.

Q37. What is the difference between eq() and get() methods in jQuery?
Ans: eq() returns the element as a jQuery object. This method constructs a new jQuery object from one element within that set and returns it. That means that you can use jQuery functions on it.

get() return a DOM element. The method retrieve the DOM elements matched by the jQuery object. But as it is a DOM element and it is not a jQuery-wrapped object. So jQuery functions can’t be used. Find out more here.

Q38. How do you implement animation functionality?
Ans: The .animate() method allows us to create animation effects on any numeric CSS property. This method changes an element from one state to another with CSS styles. The CSS property value is changed gradually, to create an animated effect.

Syntax is:

1 (selector).animate({styles},speed,easing,callback)
  • styles: Specifies one or more CSS properties/values to animate.
  • duration: Optional. Specifies the speed of the animation.
  • easing: Optional. Specifies the speed of the element in different points of the animation. Default value is “swing”.
  • callback: Optional. A function to be executed after the animation completes.

Simple use of animate function is,

1 $(“btnClick”).click(function(){
2   $(“#dvBox”).animate({height:”100px”});
3 });

Q39. How to disable jQuery animation?
Ans: Using jQuery property “jQuery.fx.off“, which when set to true, disables all the jQuery animation. When this is done, all animation methods will immediately set elements to their final state when called, rather than displaying an effect.

Q40. How do you stop the currently-running animation?
Ans: Using jQuery “.stop()” method.

Q41. What is the difference between .empty(), .remove() and .detach() methods in jQuery?
Ans: All these methods .empty(), .remove() and .detach() are used for removing elements from DOM but they all are different.

.empty(): This method removes all the child element of the matched element where remove() method removes set of matched elements from DOM.

.remove(): Use .remove() when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed.

.detach(): This method is the same as .remove(), except that .detach() keeps all jQuery data associated with the removed elements. This method is useful when removed elements are to be reinserted into the DOM at a later time.

Find out more here

Q42. Explain .bind() vs .live() vs .delegate() vs .on()
Ans: All these 4 jQuery methods are used for attaching events to selectors or elements. But they all are different from each other.

.bind(): This is the easiest and quick method to bind events. But the issue with bind() is that it doesn’t work for elements added dynamically that matches the same selector. bind() only attach events to the current elements not future element. Above that it also has performance issues when dealing with a large selection.

.live(): This method overcomes the disadvantage of bind(). It works for dynamically added elements or future elements. Because of its poor performance on large pages, this method is deprecated as of jQuery 1.7 and you should stop using it. Chaining is not properly supported using this method.

.delegate(): The .delegate() method behaves in a similar fashion to the .live() method, but instead of attaching the selector/event information to the document, you can choose where it is anchored and it also supports chaining.

.on(): Since live was deprecated with 1.7, so new method was introduced named “.on()”. This method provides all the goodness of previous 3 methods and it brings uniformity for attaching event handlers.

Find out more here

Q43. What is wrong with this code line “$(‘#myid.3’).text(‘blah blah!!!’);”
Ans: The problem with above statement is that the selectors is having meta characters and to use any of the meta-characters ( such as !”#$%&'()*+,./:;<=>?@[\]^`{|}~ ) as a literal part of a name, it must be escaped with with two backslashes: \\. For example, an element with id=”foo.bar”, can use the selector $(“#foo\\.bar”).
So the correct syntax is,

1 $(‘#myid\\.3’).text(‘blah blah!!!’);

Q44. How to create clone of any object using jQuery?
Ans: jQuery provides clone() method which performs a deep copy of the set of matched elements, meaning that it copies the matched elements as well as all of their descendant elements and text nodes.

1 $(document).ready(function(){
2   $(‘#btnClone’).click(function(){
3      $(‘#dvText’).clone().appendTo(‘body’);
4      return false;
5   });
6 });

Q45. Does events are also copied when you clone any element in jQuery?
Ans: As explained in previous question, using clone() method, we can create clone of any element but the default implementation of the clone() method doesn’t copy events unless you tell the clone() method to copy the events. The clone() method takes a parameter, if you pass true then it will copy the events as well.

1 $(document).ready(function(){
2    $(“#btnClone”).bind(‘click’, function(){
3      $(‘#dvClickme’).clone(true).appendTo(‘body’);
4   });

Q46. What is difference between prop and attr?
Ans: attr(): Get the value of an attribute for the first element in the set of matched elements. Whereas,.prop(): (Introduced in jQuery 1.6) Get the value of a property for the first element in the set of matched elements.

Attributes carry additional information about an HTML element and come in name=”value” pairs. Where Property is a representation of an attribute in the HTML DOM tree. once the browser parse your HTML code ,corresponding DOM node will be created which is an object thus having properties.

attr() gives you the value of element as it was defines in the html on page load. It is always recommended to use prop() to get values of elements which is modified via javascript/jquery , as it gives you the original value of an element’s current state. Find out more here.

Q47. What is event.PreventDefault?
Ans: The event.preventDefault() method stops the default action of an element from happening. For example, Prevents a link from following the URL.

Q48. What is the difference between event.PreventDefault and event.stopPropagation?
Ans: event.preventDefault(): Stops the default action of an element from happening.
event.stopPropagation(): Prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event. For example, if there is a link with a click method attached inside of a DIV or FORM that also has a click method attached, it will prevent the DIV or FORM click method from firing.

Q49. What is the difference between event.PreventDefault and “return false”?
Ans: e.preventDefault() will prevent the default event from occurring, e.stopPropagation() will prevent the event from bubbling up and return false will do both.

Q50. What is the difference between event.stopPropagation and event.stopImmediatePropagation?
Ans: event.stopPropagation() allows other handlers on the same element to be executed, while event.stopImmediatePropagation() prevents every event from running. For example, see below jQuery code block.

1 $(“p”).click(function(event){
2   event.stopImmediatePropagation();
3 });
4 $(“p”).click(function(event){
5   // This function won’t be executed
6   $(this).css(“background-color”, “#f00”);
7 });

If event.stopPropagation was used in previous example, then the next click event on p element which changes the css will fire, but in case event.stopImmediatePropagation(), the next p click event will not fire.

Q51. How to check if number is numeric while using jQuery 1.7+?
Ans: Using “isNumeric()” function which was introduced with jQuery 1.7.

Q52. How to check data type of any variable in jQuery?
Ans: Using $.type(Object) which returns the built-in JavaScript type for the object.

Q53. How do you attach a event to element which should be executed only once?
Ans: Using jQuery one() method. This attaches a handler to an event for the element. The handler is executed at most once per element. In simple terms, the attached function will be called only once.

1 $(document).ready(function() {
2     $(“#btnDummy”).one(“click”, function() {
3         alert(“This will be displayed only once.”);
4     });
5 });​

Q54. Can you include multiple version of jQuery? If yes, then how they are executed?
Ans: Yes. Multiple versions of jQuery can be included in same page.

Q55. In what situation you would use multiple version of jQuery and how would you include them? 
Ans: Well, it is quite possible that the jQuery plugins which are used are dependent on older version but for your own jQuery code, you would like to use newer version. So because of this dependency, multiple version of jQuery may required sometimes on single page.

Below code shows how to include multiple version of jQuery.

1 <script type=’text/javascript’ src=’js/jquery_1.9.1.min.js’></script>
2
3 <script type=’text/javascript’>
4  var $jq = jQuery.noConflict();
5 </script>
6
7 <script type=’text/javascript’ src=’js/jquery_1.7.2.min.js’></script>

By this way, for your own jQuery code use “$jq”, instead of “$” as “$jq” refers to jQuery 1.9.1, where “$” refers to 1.7.2.

Q56. Is it possible to hold or delay document.ready execution for sometime?
Ans: Yes, its possible. With Release of jQuery 1.6, a new method “jQuery.holdReady(hold)” was introduced. This method allows to delay the execution of document.ready() event. document.ready() event is called as soon as your DOM is ready but sometimes there is a situation when you want to load additional JavaScript or some plugins which you have referenced.

1
2 $.holdReady(true);
3 $.getScript(“myplugin.js”, function() {
4      $.holdReady(false);
5 });

Q57. What is chaining in jQuery?
Ans: Chaining is one of the most powerful feature of jQuery. In jQuery, Chaining means to connect multiple functions, events on selectors. It makes your code short and easy to manage and it gives better performance. The chain starts from left to right. So left most will be called first and so on.

1 ​$(document).ready(function(){
2     $(‘#dvContent’).addClass(‘dummy’);
3     $(‘#dvContent’).css(‘color’, ‘red’);
4     $(‘#dvContent’).fadeIn(‘slow’);
5 });​

The above jQuery code sample can be re-written using chaining. See below.

1 ​$(document).ready(function(){
2     $(‘#dvContent’).addClass(‘dummy’)
3           .css(‘color’, ‘red’)
4           .fadeIn(‘slow’);
5 });​

Not only functions or methods, chaining also works with events in jQuery.

Q58. How does caching helps and how to use caching in jQuery?
Ans: Caching is an area which can give you awesome performance, if used properly and at the right place. While using jQuery, you should also think about caching. For example, if you are using any element in jQuery more than one time, then you must cache it. See below code.

1 $(“#myID”).css(“color”, “red”);
2 //Doing some other stuff……
3 $(“#myID”).text(“Error occurred!”);
4

Now in above jQuery code, the element with #myID is used twice but without caching. So both the times jQuery had to traverse through DOM and get the element. But if you have saved this in a variable then you just need to reference the variable. So the better way would be,

1 var $myElement = $(“#myID”).css(“color”, “red”);
2 //Doing some other stuff……
3 $myElement.text(“Error occurred!”);
4

So now in this case, jQuery won’t need to traverse through the whole DOM tree when it is used second time. So in jQuery, Caching is like saving the jQuery selector in a variable. And using the variable reference when required instead of searching through DOM again.

Q59. You get “jquery is not defined” or “$ is not defined” error. What could be the reason?
Ans: There could be many reasons for this.

  • You have forgot to include the reference of jQuery library and trying to access jQuery.
  • You have include the reference of the jQuery file, but it is after your jQuery code.
  • The order of the scripts is not correct. For example, if you are using any jQuery plugin and you have placed the reference of the plugin js before the jQuery library then you will face this error.

Q60. How to write browser specific code using jQuery?
Ans: Using jQuery.browser property, we can write browser specific code. This property contains flags for the useragent, read from navigator.userAgent. This property was removed in jQuery 1.9.

Q61. Can we use jQuery to make ajax request?
Ans: Yes. jQuery can be used for making ajax request.

Q62. What are various methods to make ajax request in jQuery?
Ans: Using below jQuery methods, you can make ajax calls.

  • load() : Load a piece of html into a container DOM
  • $.getJSON(): Load JSON with GET method.
  • $.getScript(): Load a JavaScript file.
  • $.get(): Use to make a GET call and play extensively with the response.
  • $.post(): Use to make a POST call and don’t want to load the response to some container DOM.
  • $.ajax(): Use this to do something on XHR failures, or to specify ajax options (e.g. cache: true) on the fly.

Find out more here.

Q63. Is there any advantage of using $.ajax() for ajax call against $.get() or $.post()?
Ans: By using jQuery post()/ jQuery get(), you always trust the response from the server and you believe it is going to be successful all the time. Well, it is certainly not a good idea to trust the response. As there can be n number of reason which may lead to failure of response.

Where jQuery.ajax() is jQuery’s low-level AJAX implementation. $.get and $.post are higher-level abstractions that are often easier to understand and use, but don’t offer as much functionality (such as error callbacks). Find out more here.

Q64. What are deferred and promise object in jQuery?
Ans: Deferred and promise are part of jQuery since version 1.5 and they help in handling asynchronous functions like Ajax. Find out more here.

Q65. Can we execute/run multiple Ajax request simultaneously in jQuery? If yes, then how?
Ans: Yes, it is possible to execute multiple Ajax request simultaneously or in parallel. Instead of waiting for first ajax request to complete and then issue the second request is time consuming. The better approach to speed up things would be to execute multiple ajax request simultaneously.

Using jQuery .when() method which provides a way to execute callback functions based on one or more objects, usually Deferred objects that represent asynchronous events. Find out morehere.

Q66. Can you call C# code-behind method using jQuery? If yes,then how?
Ans: Yes. We can call C# code-behind function via $.ajax. But for do that it is compulsory to mark the method as WebMethod.

Q67. Which is the latest version of jQuery library?
Ans: The latest version (when this post is written) of jQuery is 1.10.2 or 2.0.3. jQuery 2.x has the same API as jQuery 1.x, but does not support Internet Explorer 6, 7, or 8.

Q68. Does jQuery 2.0 supports IE?
Ans: No. jQuery 2.0 has no support for IE 6, IE 7 and IE 8.

Q69. What are source maps in jQuery?
Ans: In case of jQuery, Source Map is nothing but mapping of minified version of jQuery against the un-minified version. Source map allows to debug minified version of jQuery library. Source map feature was release with jQuery 1.9. Find out more here.

Q70. How to use migrate jQuery plugin?
Ans: with release of 1.9 version of jQuery, many deprecated methods were discarded and they are no longer available. But there are many sites in production which are still using these deprecated features and it’s not possible to replace them overnight. So jQuery team provided with jQuery Migrate plugin that makes code written prior to 1.9 work with it.

So to use old/deprecated features, all you need to do is to provide reference of jQuery Migrate Plugin. Find out more here.

Q71. Is it possible to get value of multiple CSS properties in single statement?
Ans: Well, before jQuery 1.9 release it was not possible but one of the new feature of jQuery 1.9 was .css() multi-property getter.

1 var propCollection = $(“#dvBox”).css([ “width”, “height”,”backgroundColor” ]);

In this case, the propCollection will be an array and it will look something like this.

1 {
2   width: “100px”,
3   height: “200px”,
4   backgroundColor: “#FF00FF”
5 }

Q72. How do you stop the currently-running animation, remove all queued animations, and complete all animations for the matched elements?
Ans: It can be done via calling .stop([clearQueue ] [, jumpToEnd ]) method and by passing both the parameters as true.

Q73. What is finish method in jQuery?
Ans: The .finish() method stops all queued animations and places the element(s) in their final state. This method was introduced in jQuery 1.9.

Q74. What is the difference between calling stop(true,true) and finish method?
Ans: The .finish() method is similar to .stop(true, true) in that it clears the queue and the current animation jumps to its end value. It differs, however, in that .finish() also causes the CSS property of all queued animations to jump to their end values, as well.

Q75. Consider a scenario where things can be done easily with javascript, would you still prefer jQuery?
Ans: No. If things can be done easily via CSS or JavaScript then You should not think about jQuery. Remember, jQuery library always comes with xx kilobyte size and there is no point of wasting bandwidth.

Q76. Can we use protocol less URL while referencing jQuery from CDNs? 
Ans: Yes. Below code is completely valid.

1 <script type=’text/javascript’src=’//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js’></script>

Q77. What is the advantage of using protocol less URL while referencing jQuery from CDNs? 
Ans: It is quite useful when you are moving from HTTP to HTTPS url. You need to make sure that correct protocol is used for referencing jQuery library as pages served via SSL should contain no references to content served through unencrypted connections.

“protocol-less” URL is the best way to reference third party content that’s available via both HTTP and HTTPS. When a URL’s protocol is omitted, the browser uses the underlying document’s protocol instead. Find out more here.

Q78. What is jQuery plugin and what is the advantage of using plugin?
Ans: A plug-in is piece of code written in a standard JavaScript file. These files provide useful jQuery methods which can be used along with jQuery library methods. jQuery plugins are quite useful as its piece of code which is already written by someone and re-usable, which saves your development time.

Q79. What is jQuery UI?
Ans: jQuery UI is a curated set of user interface interactions, effects, widgets, and themes built on top of the jQuery JavaScript Library that can be used to build interactive web applications.

Q80. What is the difference between jQuery and jQuery UI?
Ans: jQuery is the core library. jQueryUI is built on top of it. If you use jQueryUI, you must also include jQuery.

 

Good Luck…

Writing your first jQuery Mobile app

Tags

,

 

This is the first part of jQuery Mobile Series. And in this post, You will learn a guide to start with jQuery Mobile and making your first application using jQuery Mobile. This post mainly focus on basics of jQuery mobile and provide a path to start with jQuery Mobile.

“What is jQuery Mobile”? Well, jQuery mobile is a framework created for making platform independent mobile applications. It is built using HTML5, CSS3, and the very popular jQuery library.

Lets begin… 

jQuery mobile uses HTML5 extensively so to get full advantage of jQuery mobile, we need to use HTML 5. So the very first thing include in your HTML file is “HTML5 doctype”. 

1

<!DOCTYPE html>

Next thing to tell the browser about width of your page. This is important for mobile application as if not specified that it may appear awkward on mobile devices. In the head tag of page, a meta viewport tag sets the screen width to the pixel width of the device

1

<meta name=”viewport” content=”width=device-width, initial-scale=1″>

Now lets load the jQuery mobile framework in head section. We shall use the CDN enabled links for better performance. Please take a note we need to reference jQuery mobile CSS, jQuery and jQuery mobile js file. 

<link  rel="stylesheet" type="text/css"  href="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css"/> 
<script src="http://code.jquery.com/jquery-1.8.2.min.js"></script> 
<script src="http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js"></script>

That’s all for the head section of the page. Before we move to body of the page, it is important to understand the page structure of jQuery mobile app. As seen in below image, it has 3 sections “Header”, “Content” and “Footer”. The page, its header, footer, and content are all <div> containers, which are styled by using the HTML 5 data-role attributes.

 

In the body, we shall create different page blocks, where pages are nothing but <div> elements with HTML 5 data attributes. 

Let’s first create a single page. As mentioned earlier in the post, jQuery mobile uses HTML 5. So to define a page, it uses HTML5′s data attribute “data-role=page”.

1

<div data-role=”page”>

2

</div>

Remember, we can have many such <div> elements with “data-role=page” attribute within single <body> tag. A body tag can hold multiple mobile pages too. 
Now, we shall create header, content and footer section of the page. This is again achieved using HTML 5 data-role attributes.

<div data-role="header">
</div>
<div data-role="content">
</div>
<div data-role="footer">
</div>

Let’s go ahead and put some content in all 3 sections.

<div data-role="header"><h1>Welcome!!!</h1>
</div>
  
<div data-role="content"><p>Welcome to my blog and you are reading how to write your first jQuery mobile app.</p>
</div>
  
<div data-role="footer"><h1>jQuery By Example</h1>
</div>

Putting is all together then this is how it looks.

<!DOCTYPE html>

<html>

<head>

  <meta name=”viewport” content=”width=device-width, initial-scale=1″>

  <title>My First jQuery Mobile Application</title>

  <link rel=”stylesheet” type=”text/css”  href=”http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.css”/&gt;

  <script src=”http://code.jquery.com/jquery-1.8.2.min.js”></script&gt;

  <script src=”http://code.jquery.com/mobile/1.3.1/jquery.mobile-1.3.1.min.js”></script&gt;

</head>

<body>

  <div data-role=”page”>

     <div data-role=”header”><h1>Welcome!!!</h1></div>

     <div data-role=”content”>

        <p>Welcome to my blog and you are reading how to write your first jQuery mobile app.</p>

     </div>

     <div data-role=”footer”><h1>jQuery By Example</h1></div>

  </div>

</body>

</html>

So, now when you view this page in mobile it will look like this.. 

Congratulations, You have just done with your first jQuery Mobile application.

When I started with my first app, the one thing got my attention instantly. Question came to mind about the styles applied to the page, the colors used for header, footer and content containers. As while creating the app, I have not specified any styles. Well, welcome to jQuery mobile themes. 

The framework provides 5 default basic color schemes called “color swatches“. They are named a, b, c, d and e. And by default, swatch a is used when you create a page. This provides combination of white and black colors, as seen in the previous screenshot.
Now, you must be thinking how should I change the theme? Well you can change the color swatch of your page and header/footer by using the data-theme attribute.

1

<div data-role=”header” data-theme=’b’></div>

You can also define different themes for different containers.

<div data-role="header" data-theme='b'> 
</div>
<div data-role="content" data-theme='c'>
</div>
<div data-role="footer" data-theme='b'>
</div>

Let’s change the theme to our demo and see how it looks. 

Along with these 5 predefined themes, jQuery mobile also allows you to create custom theme using ThemeRoller.

Now, lets modify the demo and add a button in header section. For now, on click of this button we will redirect user to Home.html. Although the page doesn’t exists but for demo its fine.

Defining a button is quite simple. Buttons are coded with standard HTML anchor and input elements, then enhanced by jQuery Mobile to make them more attractive and useable on a mobile device. Use anchor links (a elements) to mark up navigation buttons, and input or button elements for form submission. Lets define a navigation button in header section.

<div data-role="header">
   <a href="Home.html">Home</a>
   <h1>Welcome!!!</h1>
</div>

You can also define icons for the button using predefined icon set

provided by jQuery Mobile. To define an icon, use “data-icon” attribute.

1

<a href=”Home.html” data-icon=”home”>Home</a>

 I hope you find this post useful and good enough to start with jQuery mobile. By now, you must have an idea about creating single page, changing themes and defining buttons

Demo : http://jsbin.com/ORiREzu/11

Good luck….!!!

Useful CSS Stylesheet Tips & Tricks

Tags

Following are few CSS Tips and Tricks that I think every web developer should be aware of. You may already know many of these tricks.
Disclaimer: Not all from the below CSS tricks are written by me. Some of them are taken from different sources on internet.

1. Round Corners without images

Here is a simple CSS technique of rounding off the corners of the DIV using some css attributes. This technique will work in Firefox, Safari, Chrome and any other CSS3-compatible browser. This technique will not work in Internet Explorer.

div {
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;
    border-radius: 10px;
}

To round a specific corner (top-left or bottom-right) use below stylesheet.

div {
    -moz-border-radius-topleft: 10px;
    -webkit-border-top-left-radius: 10px;
}

Further Reading: Rounded Corner Stylesheet without images

2. Create an IE Specific Stylesheet

Create a separate stylesheet altogether and include it in the webpage whenever the client is using Internet Explorer.
IE Only

<!--[if IE]>
    <link rel="stylesheet" type="text/css" href="ie-only.css" />
<![endif]-->

IE 7 Only

<!--[if IE 7]>
    <link href="IE-7-SPECIFIC.css" rel="stylesheet" type="text/css">
<![endif]-->

Further Reading: IE Specific Stylesheet

3. Background Image of Textbox

Have you seen textboxes with background images like Search magnify glass or other images? Simply use following stylesheet to add background image to any input box.

input#sometextbox {
    background-image:url('back-image.gif');
    background-repeat:no-repeat;
    padding-left:20px;
}

Further Reading: Background Image for Textbox

4. Setting Minimum width for a page

A very handy CSS command that exists is the min-width command, whereby you can specify a minimum width for any element. This can be particularly useful for specifying a minimum width for a page.

<body>
<div id="container">

Next we create our CSS commands, so as to create a minimum width of 600px:

#container {
    min-width: 600px;
    width:expression(document.body.clientWidth < 600? "600px": "auto" );
}

The first command is the regular minimum width command; the second is a short JavaScript command that only IE understands. Do note though, this command will cause your CSS document to invalidate so you may prefer to insert it into the head of each HTML document to get round this.

5. Cross Browser Opacity

Use following stylesheet to make an element transperant by setting the opacity level.

.transparent_class {
    filter:alpha(opacity=50); 
    -moz-opacity:0.5
    -khtml-opacity: 0.5
    opacity: 0.5

6. Prevent Firefox Scrollbar Jump

Firefox does not display scroll bar if the content of page is fitting with browser height. But if the content grows, Firefox display a scroll bar their by making a scroll jump. The content of screen will be pushed left. To avoid this we can tell firefox to add scroll bar by default.

html        { overflow-y:scroll; }

7. Rotate Text using CSS

This example rotates text 90 degrees counterclockwise.

The rotation property of Internet Explorer’s BasicImage filter can accept one of four values: 0, 1, 2, or 3 which will rotate the element 0, 90, 180 or 270 degress respectively.

.rotate-style {
        /* Safari */
        -webkit-transform: rotate(-90deg);
        /* Firefox */
        -moz-transform: rotate(-90deg);
        /* Internet Explorer */
        filter: progid:DXImageTransform.Microsoft.BasicImage(rotation=3);
}

8. CSS for Handheld/Mobile devices

A separate CSS document can be created for PDAs and mobile phones, and only activated when one of these devices is being used to access your site. More and more websites are creating separate CSS documents for printing, so web pages automatically become print-friendly when users choose to print them. You can also do the same for handheld devices.
The following command is used to call up the CSS document for handhelds:

<link type="text/css" rel="stylesheet" href="handheldstyle.css" media="handheld" />

9. Change Text Selection Color

By default, browsers uses blue color as the text selection. You can change this color to match your website theme.

/* Mozilla based browsers */
::-moz-selection {
       background-color: #FFA;
       color: #000;
}
/* Works in Safari */
::selection {
       background-color: #FFA;
       color: #000;
}

10. Remove Dotted Link Borders

Dotted borders around links are an accessibility feature most browsers have by default. It’s for users who must or choose to navigate by keyboard, there is a visual style applied to those links when “tabbed” to. These borders also show up when the link is clicked (in it’s “active” state), and can be an eyesore depending on the design (especially when using something like CSS image replacement, the borders span the length of the screen). You can remove them with this:

a:active {
    outline: none;
}

11. Centering a Website

Most of website uses this technique to center the content.

<body>
  <div id="page-wrap">
    <!-- all websites HTML here -->
  </div>
</body>
#page-wrap {
     width: 800px;
     margin: 0 auto;
}

12. CSS Drop Caps

This paragraph has the class “introduction”. If your browser supports the pseudo-class “first-letter”, the first letter will be a drop-cap.

p:first-letter {
       font-size : 300%;
       font-weight : bold;
       float : left;
       width : 1em;
}

13. Attribute-Specific Icons

CSS Attribute selectors are very powerful giving you many options to control styles of different elements e.g. you can add an icon based on the href attribute of the a tag to let the user know whether link points to an image, pdf, doc file etc.

a[href$='.doc'] { 
    padding:0 20px 0 0
    background:transparent url(/graphics/icons/doc.gif) no-repeat center rightright; 

14. Capitalize Text

This trick is especially useful for displaying title of an article on a web page with all its words starting with capital letter.

text-transform: capitalize
text-transform: lowercase
text-transform: uppercase
  • none: No capitalization. The text renders as it is. This is default
  • capitalize: Transforms the first character of each word to uppercase
  • uppercase: Transforms all characters to uppercase
  • lowercase: Transforms all characters to lowercase
  • inherit: Specifies that the value of the text-transform property should be inherited from the parent element

15. CSS Text Shadow

Regular text shadow:

p { text-shadow: 1px 1px 1px #000; }

Multiple shadows:

p { text-shadow: 1px 1px 1px #000, 3px 3px 5px blue; }

The first two values specify the length of the shadow offset. The first value specifies the horizontal distance and the second specifies the vertical distance of the shadow. The third value specifies the blur radius and the last value describes the color of the shadow:

1. value = The X-coordinate
2. value = The Y-coordinate
3. value = The blur radius
4. value = The color of the shadow

Using positive numbers as the first two values ends up with placing the shadow to the right of the text horizontally (first value) and placing the shadow below the text vertically (second value).

The third value, the blur radius, is an optional value which can be specified but don’t have to. It’s the amount of pixels the text is stretched which causes a blur effect. If you don’t use the third value it is treated as if you specified a blur radius of zero.

16. Using !important

Experienced CSS programmers are usually aware of this but beginners do miss out on this !important CSS rule. By adding !important to your CSS rule, you can increase its precedence over other subsequent rules. e.g. in below code, background-color will be blue and not red due to !important.

.page { background-color:blue !important;   background-color:red; } 

17. Print Page Breaks

While most of the internet users prefer to read content online but some of your users might like to print your article. With CSS you can control the page breaks within content just add this CSS class to your stylesheet and add this class to any tag which you would like to print on next page.

.page-break        { page-break-before:always; } 

18. CSS Pointer Cursors

This trend has caught up lately. All user interface elements on a web page that can be clicked by user have their cursor similar to that of hyperlink. Here’s the CSS trick to do that.

input[type=submit],label,select,.pointer { cursor:pointer; } 

19. Set a Consistent Base Font Size

Setting the font-size property to 62.5% in body tag makes 1em equal to 10px. This lets you use em easily as you can find out the font-size in pixels from em values.

body{ font-size:62.5%; } 

20. Perfect Page-Printing with CSS

An overlooked feature on the website is the “print this article” link. There are many people who use the Internet who still like to print out useful articles and store them in paper form. In order to pull this off, you need to use CSS/XHTML page breaks.

@media all
       .page-break    { display:none; } 
  
@media print
       .page-break    { display:block; page-break-before:always; } 

Good Luck…!!!