Showing posts with label jquery. Show all posts
Showing posts with label jquery. Show all posts

Thursday, 18 August 2016

How to get visitor location with JavaScript ?

How to get visitor location with JavaScript ?

Today there are lots Free/Paid API avaiable which give you client information.
Following are two example which give you client information like city, country, country code, ip, local date time, timezone etc with javascript.
Question: How to get visitor location javascript with
<script src=""></script>
$(document).ready( function() {
   $.getJSON("", function(result){


{  "ip": "",
  "country_code": "IN",
  "country_name": "India",
  "region_code": "PB",
  "region_name": "Punjab",
  "city": "Mohali",
  "zip_code": "",
  "time_zone": "Asia/Kolkata",
  "latitude": 30.78,
  "longitude": 76.69,
  "metro_code": 0

Question: How to get visitor location javascript with

<script src=""></script>
$(document).ready( function() {
   $.getJSON('', function(data){

  {"ip": "",
  "hostname": "No Hostname",
  "city": "Mohali",
  "region": "Punjab",
  "country": "IN",
  "loc": "30.7800,76.6900",
  "org": "AS17917 Quadrant Televentures Limited"

Wednesday, 20 January 2016

jQuery UI Interview Questions and Answers

 jQuery UI Interview Questions and Answers

Question: What is jQuery UI? It is JavaScript Library which is collection of jQuery widgets like datepicker, tabs, autocomplete etc. We can also add effects, interactions (drag, drop, resize) on widgets.

  Question: What widets are available in jQuery UI?
  1. Accordion
  2. Autocomplete
  3. Button
  4. Datepicker
  5. Dialog
  6. Menu
  7. Progressbar
  8. Selectmenu
  9. Slider
  10. Spinner
  11. Tabs
  12. Tooltip

Question: What are different effects available in jQuery UI
  1. Add Class
  2. Color Animation
  3. Easing
  4. Effect
  5. Hide
  6. Remove Class
  7. Show
  8. Switch Class
  9. Toggle
  10. Toggle Class

Question: In which language, JQuery UI is written?

Question: Is JQuery UI opensource?
Question: What is current stable version of JQuery UI?
1.11.4 / dated 11 March 2015

Question: From where we can download the jQuery UI

Question: Can we download custom widgets from jQuery UI
Yes, We can.

Question: How to add CSS property on last div?
$('div:last').css({backgroundColor: 'green', fontWeight: 'bolder'});

Question: What is $.noConflict()?
<script src="" type="text/javascript"></script>
<script type="text/javascript">

When we call to $.noConflict(). Old references of $ are saved during jQuery initialization, noConflict() simply restores them.

Question: Can we use another variable instead of $ in jQuery? If yes, How?
Yes, we can.
var jQ = jQuery.noConflict();
/** Now use jQ instead of $ **/
jQ( "div#pid" ).hide();

Question: How to remove close button on the jQuery UI dialog using CSS?
.ui-dialog-titlebar-close {
  visibility: hidden;

Question: How to remove close button on the jQuery UI dialog using JavaScript?
   closeOnEscape: false,
   open: function(event, ui) { $(".ui-dialog-titlebar-close", ui.dialog | ui).hide(); }

Question: How to initialize a dialog without a title bar?
var dialogOpts=[]
//Remove the title bar

Question: How to call Hook into dialog close event in jQuery UI?
$('div#contentId').on('dialogclose', function(event) {
     //console.log('closed event called');

Question: How to Download jQuery UI CSS from Google's CDN?

Question: How to "Change button text" in JQuery?
jQuery Version < 1.6
$("#elementId").attr('value', 'Save'); //versions older than 1.6

jQuery Version > 1.6
$("#elementId").prop('value', 'Save'); //versions newer than 1.6

Question: How can I disable a button in a jQuery ?
$('#divId').attr("disabled", true);

Question: How do I keep jQuery UI Accordion collapsed by default?
$("#divId").accordion({ header: "h4", collapsible: true, active: false });

Question: How to call a dragable widget?
// Make #draggable draggable
$(function () {

Question: How do I disable a jquery-ui draggable of widget?
//myObject is widget object.
myObject.draggable( 'disable' );

OR, you can set during the initalization
    draggable: false

How to remove JQuery UI Autocomplete Helper text?
.ui-helper-hidden-accessible { display:none; }

Question: How to set year in DatePicker?
    yearRange: '1950:2013', 
   changeMonth: true,
   changeYear: true,
   showButtonPanel: true,

Question: How to set current Date in Date Picker?
$(".datepickerClass").datepicker('setDate', new Date());

Question: How to Change Date Format in jQuery UI DatePicker?
var date = $('#datepickerDivId').datepicker({ dateFormat: 'dd-mm-yy' }).val();

Friday, 1 January 2016

jQuery Mobile interview questions and answers

jQuery mobile interview questions and answers

jQuery Mobile is a UI framework which is written in javaScript language and used for creating mobile web applications. It works on all popular smartphones and tablets. jQuery Mobile uses HTML5 & CSS3.

What is Initial release of JQuery Mobile?
October 16, 2010

Question: What is Latest version of jQuery Mobile?
Version: 1.4.5
Dated: October 31, 2014

Question: In which language, jQuery mobile is written?

Question: Where it is used?
It is "Mobile application framework" which is used for creating mobile web applications.

Question: What is offical website of jQuery Mobile?

Question: What are Features of jQuery Mobile?
  • Compatible with all major desktop browsers as well as all major mobile platforms (Android, iOS, Windows Phone, Blackberry, WebOS, Symbian)
  • Built on top of jQuery core.
  • Lightweight to optimize speed.
  • The same underlying codebase will automatically scale to any screen.
  • HTML5-driven.
  • AJAX-powered navigation with animated page.
  • UI widgets

Question: Why Use jQuery Mobile?
1. Write Less, Do more
2. Its works on Android, Blackberry, iOS and Iphone
3. Its optimized

Question: Describe few HTML tags used in jQuery Mobile?
data-role="page": Page displayed in the browser.
data-role="header": Creates a toolbar at the top of the page.
data-role="main": Content of the page, like text, images, buttons and forms etc.
"ui-content": Adds extra padding and margin inside the page content
data-role="footer": creates a toolbar at the bottom of the page

Question: How to Add Back Button?
<a class="ui-btn" data-rel="back" href="">Go Back</a>

Question: What is jQuery Mobile Themeing?
jQuery Mobile provides a powerful theming that allows developers to customize color schemes & CSS aspects of UI features.

Wednesday, 16 September 2015

jQuery Ajax Interview Questions and Answers for Experienced

jQuery Ajax Interview Questions and Answers for Experienced

Question: What is the difference between jQuery.get() and jQuery.ajax()?
$.get( "/ajax/add-user", { name: "Arun", company: "", gender:"Male" } );
$.get executes an Ajax request with using of GET Method.

    type: "POST",
    url: "/ajax",
    data: "name=Arun&",
    success: function(msg){

$.ajax you full control over the Ajax request. In this you can use any method like GET or POST. I think you should use this only, if the other methods did not fulfill your requirement.
You can do lot of customization in this like caching and Ajax method etc

Question: What is the use of jQuery load method?
It is AJAX method which is used to load the data from a server and assign the data into the element without loading the page.

Question:What are the security issues with AJAX?
  1. Source code written in ajax easily visiable.
  2. Attrackers can send the the data to same API Call
  3. Attrackers can view the Request/Response in Ajax call.
  4. Attacker can view the full response and can hit and trial.

Question: How many types of ready states in ajax?
0: Request not initialized
1: Server connection established
2: Request received
3: Processing request
4: Request finished and response is ready

Question: List Some Popular Ajax Frameworks?.
  1. jQuery.
  3. Prototype
  4. MooTools
  5. ExtJS
  6. Qooxdoo
  7. Yahoo! UI Library (YUI)
  8. MochiKit
  9. Midori
  10. The Dojo Toolkit

Question: What exactly is the W3C DOM?
The W3C Document Object Model (DOM) is defined by the W3C.
The DOM is a platform and language-neutral interface that allows programs and scripts to dynamically access/update the content of a document.

Question: What is the XMLHttpRequest object in AJAX?
It is way to update the web content from server without reloading the page.

Question: How can we abort the current XMLHttpRequest in AJAX?
use abort() function. For Example:
var xhr;    
xhr = $.ajax({
    url: 'ajax/get-user-details/user_id/3',
    success: function(data) {

//Abort the Ajax call
if(xhr && xhr.readystate != 4){

Question: How to cancel all the active ajax call?
Every time you create an ajax request you should use a variable to store it, you can use array object to store multiple ajax.
Now you can use abort() function to abort each ajax call.

Question: How to debug Ajax call
You can use debug tools of browser.
like firebug in Mozilla.
Inspect element in Google Chrome

Question: How to convert an object to a string?
var javascriptObject = {name: "Web", "URL": ""};
JSON.stringify(javascriptObject, null, 2);

Question: How to convert an string to a object?
var javascriptObject = '{name: "Web", "URL": ""}';
JSON.parse(javascriptObject, null, 2);

Question: How can I add a custom HTTP header to ajax request with js or jQuery?
    url: '/ajax/get-user-details/user_id/3',
    headers: { 'x-my-custom-header': 'some value' },
    success: function(data) {

Question: How to determine if ajax timeout error comes?
     url: '/ajax/get-user-details/user_id/3',
    type: "GET",
    dataType: "json",
    timeout: 1000,
    success: function(data) { 
    error: function(x, t, m) {
        if(t==="timeout") {
            console.log("got timeout");
        } else {

Question:How to send an https ajax call on http page?
Add the Access-Control-Allow-Origin header from the server

Friday, 17 July 2015

Jquery Interview Questions and Answers for experienced

jquery interview questions and answers for experienced
Question: What is jQuery?
jQuery is a fast, small and feature-rich JavaScript library.
jQuery makes things like HTML document traversal and manipulation, animationevent handling and Ajax much simpler with an easy-to-use API.
It works across a multitude of browsers.

Question: What is Ajax?
Ajax( Short form of Asynchronous JavaScript and XML) is a Web development techniques used on the client-side to create Synchronous OR asynchronous Web applications. It is used to get the data from server without refresh the page.

Question: What is Iframe?
Iframe is an HTML document embedded inside another HTML document on a website. We can embed one OR many iframe in one website.

Question: What is element in HTML?
An HTML element is an individual component of an HTML document or web page.
For example, p,div,span etc know as element.
when these surrounded by angle brackets know as HTML Tags.

Question: What is event in jQuery? Doing any thing, known as event.
For Example, Click event, mouseover event, blur event, double click event etc.

Question: What is jQuery event?
A jQuery object is array-like which means that it contains zero or more indexes.

Question: How to parse a JSON String?
var obj = jQuery.parseJSON( '{ "name": "John" }' );

Question: How to communicate between iframe and the parent site?
With same domain and same port/protocol
you can use window.opener to change in parent window from child window.
you can use document.getElemetById('#iframeId') to change in child window from parent window.
With different domain OR different port/protocol
You have to use cross-document messaging.

Question: How can I select an element by name or class or id with jQuery?
Select by name

Select by class name

Select by classId

Question: How to show the preview an image before it is uploaded to server?
To show the preview you need to use "FileReader" javascript function.
See Demo:

Question: How to get html tags from string?
var re = /(<([^>]+)>)/ig; 
    var str = '


'; var m; while ((m = re.exec(str)) !== null) { if (m.index === re.lastIndex) { re.lastIndex++; } } console.log(re);

Question: What is use $.each? Give examples?
It is similar to foreach in jQuery.
you can use $.each for normal array OR list of elements. For Example:
$('a.myclass').each(function(index, value){

var numberArray = [0,1,2,3,4,5];
jQuery.each(numberArray , function(index, value){
     console.log(index + ':' + value); 

Question: What's the difference between jquery.js and jquery.min.js?
Both are same.
only difference jquery.min.js is minified file which have no space, tab.

Question: How to add Email Validation in jQuery?
function IsValidEmail(email) {
  var regex = /^([a-zA-Z0-9_.+-])+\@(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  return regex.test(email);
console.log(IsValidEmail('[email protected]'));
console.log(IsValidEmail('[email protected]'));

Question: How to get nth jQuery element?
use eq function.

Question: How to remove a row from table?

Question:How to bind shortcut-keys with jQuery?
To bind Ctrl+f to a functionName.
$(document).bind('keydown', 'ctrl+f', functionName);

You can check also:

Question: How to convert array to JSON?
You can use stringify.
var yourArray = Array('1','2','3','4');
var myJsonString = JSON.stringify(yourArray);

Question: How to check if a div exists with jquery?
if($("div#idName" + name).length > 0) {
  /** It is exist **/

Question: How to call a function after 3 seconds?
/** Do here **/

/** Do here **/    
  }, 3000);

Question: How to prevent caching in Ajax?
After loading of jQuery, add the below code at the top of all ajax call.
$.ajaxSetup({ cache: false });

Saturday, 11 April 2015

How can I check DOM is ready in jQuery

How can I check DOM is ready in jQuery

Question: What is DOM?
The Document Object Model (DOM), is a model for representing and interacting with an XML, XHTML and HTML document.

Question: What is meaning of DOM is ready?
DOM is ready means html, images, css and java-Script are loaded fully.

Question: Why need to check if DOM is ready OR NOT?
Some times, we need to do the some modification in html tags like p,div and image etc.
We can change the DOM only after if DOM is loaded.

Following are 3 methods to check DOM() is fully loaded?
Method 1:
      //consol.log('DOM IS FULLY loaded');


Method 2:
  //consol.log('DOM IS FULLY loaded');

Method 3:
if ( jQuery.isReady ) {  
    //consol.log('DOM IS FULLY loaded');

Wednesday, 25 March 2015

How to add new row in existing table using jQuery

How to add new row in existing table using jQuery

I have following existing table

<table id="myTestTable"> <tbody> <tr>.......</tr> <tr>.......</tr> <tr>.......</tr> <tr>.......</tr> </tbody> </table>

Currently, It have Total 4 Rows.
I want to add one more row, Just after the last table row. Which should look like below:

<table id="myTestTable"> <tbody> <tr>.......</tr> <tr>.......</tr> <tr>.......</tr> <tr>.......</tr> <tr>.......</tr> </tbody> </table>

Now, how can I add new table-row in existing table in single line?.

Step 1: Add jQuery file in webpage.
<script src="//"></script>

Step 2: Just add following script when you want to add new table row in existing table.
$('table#myTestTable tr:last').after('...');
It will add one new row in exiting table @ the end each time you call this script.

Monday, 23 March 2015

How to Include a JavaScript file in another JavaScript file?

How to Include a JavaScript file in another JavaScript file?

Including a javascript file in another javascript file is common in web development.
Because many times we include the javascript file at run time on the behalf of some conditions.

So, we can achieve this using javascript as well as using jQuery.

Method 1: Use JavaScript to include another JavaScript file.
Step 1: Add following function in web page.
function loadScript(url)
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

Step 2:just call the below loadScript function, Where you want to include the js file.

Method 2: Use jQuery to include another javasScript file .
Step 1: Add jQuery File in your webpage.
<script src="//"></script> Step 2: Just call the  getScript  function functions.

Saturday, 21 March 2015

How can I get query string values in JavaScript and jQuery?

How can I get query string values in JavaScript and jQuery?

I want to get the values from the Query String (means from URL), values are dynamic but query string variable is constant.

Suppose, I have following URL:

Now, I want to get the value of following query string.
id //currently it is 10, but it is dynamic.
c //currently it is country, but it is dynamic.

Solution 1: Get the value of query string with JavaScript.
Step 1: Add following javaScript function in your page.
function getParam(name) {
    name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
    var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
        result = regex.exec(;
    return result === null ? "" : decodeURIComponent(result[1].replace(/\+/g, " "));

Step 2: Use getParam function to get the query string values. See below:

Solution 2: Get the value of query string with jQuery.
Step 1: Add jQuery File in your webpage.
<script src="//"></script>

Step 2: Add following jQuery function in web page.
  $.getParamJquery = function(name, url) {
      if (!url) {
       url = window.location.href;
      var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(url);
      if (!results) { 
          return undefined;
      return results[1] || undefined;

Step 3: Use getParamJquery function to get the query String values. See below:

Saturday, 3 January 2015

How to Add attribute in A-Tag using jQuery

How to Add attribute in A-Tag using jQuery

Following is HTML:
<div class="links">
<a href="">link1</a>
<a href="">link2</a>

Output Should be:
<div class="links">
<a href="" target="_blank">link1</a>
<a href="" target="_blank">link2</a>

Following are Simple ways to do this Using jQuery.
$(document).ready(function() {
    $('div.links p a').attr('target', '_blank');

We can also add custom attribute in any html tag.

Monday, 27 October 2014

Lightbox vs Fancybox

Lightbox vs Fancybox

Lightbox: It is a lightweight jQuery plugin  used for showing images in overlay on the website.

Following are feature of Lightbox plugin.
  1.     Show image in overlay.
  2.     Show the Title of image in Overlay.
  3.     Show image gallery in overlay with "Left", "Right" Button.
  4.     In Image gallery, It support image movement with "Left" & "Right" keys.
  5.     Open Iframe in overlay does not support.
Demo & Download 

Fancybox: It is jQuery plugin used for displaying images, videos (like youtube) on  iframe and map etc in overlay on the website.

Following are feature of  Fancybox plugin.
  1.     Show image in overlay.
  2.     Show the Title of image in Overlay.
  3.     Show image gallery in overlay with "Left", "Right" Button.
  4.     In Image gallery, It support image movement with "Left" & "Right" keys.
  5.     Open Iframe in overlay - You can play youtube video in overlay.
  6.     Support Ajax Processing Data.
  7.     Play SWF Files in overlay.
  8.     Google Map in Iframe.
  9.     Support callback function when open pages in overlay.
  10.     Handling "Not existing URL/Image" by plugin itself.

Saturday, 22 February 2014

Firebase Chat with Facebook and Twitter Integration

FireBase Chat
1). Its Free
2). You can integrate with Facebook/Twitter/Github etc
3) You can manage Chat (Can View/Update/Delete)
4) You can export chat in Json Form
5) API Available



How to setup firebase chat
1) Register to
2) Login to your firebase account similar to
3) Go to Dashboard=>Simple Account
a) Add list of domains where your chat will be run, (for example localhost,
b) Set "Authentication Providers"
Here you can enable provider (Facebook|Twitter etc)
Enable the checkbox and put the required credentials

For facebook
i) Create a app
ii) In Site URL put ""
iii) In "Site and Review", Enable the app for public
iv) Copy your "App ID" and "App Secret" from "Settings" and paste in ">Simple Login=>Facebook"

For Twitter
i) Create a App in
ii) In Callback URL set ""
iii) Copy "API key" and "API secret" from twitter apps and paste in ">Simple Login=>Twitter" (Twitter Consumer Key,Twitter Consumer Secret)

4) Open Below URL's
a) Click on "Launch demo" of Facebook Link
b) Click on "Launch demo" of Twitter Link

Friday, 6 September 2013

jQuery datepicker first week monday

jQuery datepicker first week monday

jQuery DatePicker is a Plugin provided by, This date picker enable user to select the dates like Date of Birth, Date of joining and select two dates. It have excellent feature like change the date format of date, disable the selection of previous date, disable the selection of next year, show the dates picker in different languages like chinse. You can do the lot of custom changes. All custom changes are available in their website.

Now, many different countries use different date format like USA start date with month, Indian start date  with day and some country start date with year. This is 100% configurable in the jQuery plugin. you can set the dateFormat while creating the instance of date picker.

By default, the Datepicker opens in a small overlay onFocus and closes automatically onBlur or when a date is selected. For an inline calendar, simply attach the Datepicker to a div or span.

While creating the instance of datepicker, you can also change the what day of the week. You can start first day as Sunday OR Monday as per your requirement.n See the Following Example.

Change the first week from Sunday=>Monday 

Just set the firstDay:1 which is 0 by default
    changeMonth: true, 
    changeYear: true, 
    dateFormat: "mm/dd/yy", 
    firstDay: 1 

Another Example for multiple date option
    constrainInput: true,   // prevent letters in the input field
    minDate: new Date(),    // prevent selection of date older than today
    showOn: 'button',       // Show a button next to the text-field
    autoSize: true,         // automatically re-size the input field 
    altFormat: 'yy-mm-dd',  // Date Format used
    beforeShowDay: $.datepicker.noWeekends,     // Disable selection of weekends
    firstDay: 1 // Start with Monday


How to Create A Basic Plugin In JQuery

How to Create A Basic Plugin In JQuery

Today in all web application, We use jQuery plugin like image slider, Date Picker, Table Plugin, Multiple Month Selector and Upload image through Ajax etc.

In our web application we use one OR more jQuery plugins.

jQuery Plugin creation is very simple and interesting once you can learn how to create. To be expert in jQuery plugin you must know the basic of HTML/HTML5/CSS/CSS3 and jQuery. When you start learning plugin, it seems difficult but after continue 1-2hour you will be start understanding and taking quite interest.

today, all web application use jquery plugin whether it is made in PHP OR ASP. Also if you are expert in jQuery and jQuery plugins you have excellent career as a UI developer. today most of MNC companies hiring UI developer  because UI developer can handle all UI stuff whether web application is created in PHP or ASP.
So, Start enjoying the creation of jQuery plugin, trust me its quite easy just start with confidence.
Confidence is required in all the fileds....

Following plugins gives you max height/width of div.
/** create a jQuery plugin **/
        var max =0; 
            max = Math.max(max, jQuery(this).height()); 
        return max;  

        var max_width =0; 
            max_width = Math.max(max_width, jQuery(this).width());                   
        return max_width; 
/** create a jQuery plugin **/

/** How to use a jQuery plugin **/
  //alert('Max Height: ' + jQuery('div').maxHeight());
  //alert('Max Width: ' + jQuery('div').maxWidth());
/** How to use jQuery plugin **/
Div 1</div>
Div 2</div>
Div 3</div>

Just Copy the Above code snippets and past in any html and access that html through Browser. Just look at once try to understand, you will start understanding.