jQuery Guide

This guide has the information you need to know about jQuery to get started. 

Basics

  1. jQuery is a library of javascript functions that you can use in your code. If you know the basics of javascript then you will be able to easily learn jQuery. 
  2. You can very easily apply different operations and formatting on different tags in your html code. For ex: If you want to hide a specify elements(lets say <p>) upon click a link. You can easily do this via jQuery. 
  3. To use jQuery you have to find the tag(selector) on which you have to perform the action. Basic syntax is:
    1. $(selector).action(
      1. To access jQuery library $ is used. We can use jQuery in place of $. At some places we do use jQuery instead of a $, we will explore it in more details at later point in the tutorial. 
      2. A (selector) or tag in the html document. 
      3. action() specifies the operation to be performed on the selected tag.
  4. There are certain ways to find the html element. These methods are similar to finding elements in CSS.
    1. $(“h1”) - This method will select the element h1.
    2. $(“#format”) - This method will select the element whose id=“format” in the html page.
    3. $(“.formatter”) - This method will select the element whose class = “formatter” in the html element. 
  5. To use jQuery library you can either download it and include it your source code. Or else you can refer it from its hosted location. One such location is: http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js
  6. Hence you should include this library reference in the script tag like this:
    1. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> 
  7. And it should be included in your head tag like this:
    1. <head>
    2. <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
    3. </head>
  8. Quick Notes:
    • jQuery uses $ sign as a shortcut for jQuery
    • jQuery is Client side scripting
  9. What if other JavaScript frameworks also use the $ sign as a shortcut?
  10. If two different frameworks are using the same shortcut, one of them might stop working.
    The jQuery team have already thought about this, and implemented the noConflict() method.
    The noConflict() method releases the hold on the $ shortcut identifier, so that other scripts can use it.
    $.noConflict();
    jQuery(document).ready(function(){
      jQuery("button").click(function(){
        jQuery("p").text("jQuery is still working!");
      });
    });


jQuery Events

jQuery Mouse Events
Some of the jQuery methods are common and can be executed on desired tags. All the methods attaches the event handlers on the html element on which they are attached. Once that action is performed the event handler is called and it performs the set of steps on the corresponding html element. 
  1. .click() - Action is performed when html tag/selector is clicked.
  2. .dblclick() - Action is performed when html tag/selector is double clicked
  3. .focus() - Action is performed when html/tag selector is focused on.
  4. .change() - Action is performed when html tag/selector value changes. It is limited to tags: <input>, <textarea>, <select>
  5. .mouseenter() - Action is performed when mouse enters the html tag/selector. 
  6. .mouseleave() - Performs opposite action as compared to mouse enter.
  7. .hover() - Perform action when mouse is hovered over the corresponding html tag/selector.
  8. .focusout() - Event is executed when the focus moves away from corresponding html tag/selector.
  9. .mousedown() - Event is executed when mouse button is clicked on the html tag/selector.
  10. .mousemove() - Event is executed when mouse move in the html tag/selector.
  11. .mouseout() - Event is executed when mouse moves out of the html element. 
  12. .mouseover() - Event is executed when mouse moves over the html element. 
  13. .mouseup() - Event is executed when mouse is over the html element and is released. 
  14. .toggle() - This event is deprecated in the jQuery 1.8. 

jQuery Keyboard events:
  1. .focusout() - Event is invoked when any element or an element below it loses focus. It is different from blur since it supports losing focus from the child elements.
  2. .keydown() - Event is invoked when any key is pressed. Any element in focus will receive the actions when this event is executed. 
  3. .keypress() - Similar to keydown but following keys will not register key press event: shift, Del, Esc
  4. .keyup() - Event is invoked when a key is released.Because of event bubbling all the key presses will be propagated to the document element. For specific elements, we can use .keypress().

Document Rendering Events:
    • .load() - Action is performed when html tag/selector is loaded.
    • .ready() - Action is performed when the DOM is ready or the document is ready. It doesn’t work well with .load since that operation will start performing its operation as soon as the element is available. However, .ready is not going to execute its action till entire DOM is available. When this function is called then we should use $.noConflict() to avoid the namespace conflicts and we have to use jQuery in place of $. 
    • .unload() - Action to be performed when the user intends to go away from the page. The action of going away include:
      • - click on forward and back button.
      • - Refresh a page
      • - clicking on exit browser button. 

Keyboard Events:
    • 1) .focusout() - Event is invoked when any element or an element below it loses focus. It is different from blur since it supports losing focus from the child elements.
    • 2) .keydown() - Event is invoked when any key is pressed. Any element in focus will receive the actions when this event is executed. 
    • 3) .keypress() - Similar to keydown but following keys will not register key press event: shift, Del, Esc
    • 4) .keyup() - Event is invoked when a key is released.Because of event bubbling all the key presses will be propagated to the document element. For specific elements, we can use .keypress().

Commonly Used jQuery Event Methods
    • $(document).ready(): The $(document).ready() method allows us to execute a function when the document is fully loaded. This event is already explained in the jQuery Syntax chapter.
    • click()
      • The click() method attaches an event handler function to an HTML element.
      • The function is executed when the user clicks on the HTML element.
    • dblclick()
      • The dblclick() method attaches an event handler function to an HTML element.
      • The function is executed when the user double-clicks on the HTML element:
    • mouseenter()
      • The mouseenter() method attaches an event handler function to an HTML element.
      • The function is executed when the mouse pointer enters the HTML element:
    • mouseleave()
      • The mouseleave() method attaches an event handler function to an HTML element.
      • The function is executed when the mouse pointer leaves the HTML element:
    • mousedown()
      • The mousedown() method attaches an event handler function to an HTML element.
      • The function is executed, when the left mouse button is pressed down, while the mouse is over the HTML element:
    • mouseup()
      • The mouseup() method attaches an event handler function to an HTML element.
      • The function is executed, when the left mouse button is released, while the mouse is over the HTML element:
    • hover()
      • The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods.
      • The first function is executed when the mouse enters the HTML element, and the second function is executed when the mouse leaves the HTML element:
    • focus()
      • The focus() method attaches an event handler function to an HTML form field.
      • The function is executed when the form field gets focus:
    • blur()
      • The blur() method attaches an event handler function to an HTML form field.
      • The function is executed when the form field loses focus:


jQuery DOM Manipulation: One very important part of jQuery is the possibility to manipulate the DOM. jQuery comes with a bunch of DOM related methods that make it easy to access and manipulate elements and attributes
    • text() - Sets or returns the text content of selected elements
    • html() - Sets or returns the content of selected elements (including HTML markup)
    • val() - Sets or returns the value of form fields
    • The jQuery attr() method is used to get attribute values.


Call back functions

$("#btn1").click(function(){
    $("#test1").text(function(i,origText){
        return "Old text: " + origText + " New text: Hello world!
        (index: " + i + ")"; 
     });
 });
We can have similar callback functions for the other methods: text, html, val
  • remove() - Removes the selected element (and its child elements)
  • empty() - Removes the child elements from the selected element

Call Back Function example:
$("#div1").remove();
$("p").remove(".italic");


jQuery Methods


  • jQuery addClass() Method
The following example shows how to add class attributes to different elements. Of course you can select multiple elements, when adding classes:
Example
$("button").click(function(){
    $("h1,h2,p").addClass("blue");
    $("div").addClass("important");
});

  • jQuery removeClass() Method
The following example shows how to remove a specific class attribute from different elements:
Example
$("button").click(function(){
    $("h1,h2,p").removeClass("blue");
});

  • jQuery toggleClass() Method
The following example will show how to use the jQuery toggleClass() method. This method toggles between adding/removing classes from the selected elements:
Example
$("button").click(function(){
    $("h1,h2,p").toggleClass("blue");
});

  • Set a CSS Property
$("p").css("background-color","yellow");


  • Set Multiple CSS Properties
$("p").css({"background-color":"yellow","font-size":"200%"});


  • jQuery Dimension Methods
jQuery has several important methods for working with dimensions:
    • width()
    • height()
    • innerWidth()
    • innerHeight()
    • outerWidth()
    • outerHeight()

  • Traversing Up the DOM Tree
Three useful jQuery methods for traversing up the DOM tree are:
    • parent(): The parent() method returns the direct parent element of the selected element. And it goes up only a single level.
    • parents(): Find all the parents.
    • parentsUntil(): Find the parents till a specific html or class or id specified
$(document).ready(function(){
     $("span").parentsUntil("div");
});


  • Traversing Down the DOM Tree
Two useful jQuery methods for traversing down the DOM tree are:
    • children()
    • find()
The children() method returns all direct children of the selected element and it traverses only a single level down. 

The find() method returns descendant elements of the selected element, all the way down to the last descendant.
$(document).ready(function(){
     $("div").find("span");
});

  • Traversing Sideways in The DOM Tree
    • siblings(): Returns all the siblings of the current element. 
    • next()
    • nextAll()
    • nextUntil()
    • prev()
    • prevAll()
    • prevUntil()

  • jQuery prev(), prevAll() & prevUntil() Methods
The prev(), prevAll() and prevUntil() methods work just like the methods above but with reverse functionality: they return previous sibling elements (traverse backwards along sibling elements in the DOM tree, instead of forward).
JQuery Filtering
The first() method returns the first element of the selected elements.


  • jQuery + Ajax: 
<script>
$(document).ready(function(){
    $("button").click(function(){
       $("#div1").load("demo_test.txt");
  });
});
</script>

<div id="div1"><h2>Let jQuery AJAX Change This Text</h2></div>
<button>Get External Content</button>


  • jQuery load() Method
The load() method loads data from a server and puts the returned data into the selected element.
Syntax:
$(selector).load(URL,data,callback);
- The required URL parameter specifies the URL you wish to load.
- The optional data parameter specifies a set of querystring key/value pairs to send along with the request.
- The optional callback parameter is the name of a function to be executed after the load() method is completed.
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").load("demo_test.txt");
  });
});
</script>


  • jQuery $.get() Method
The $.get() method requests data from the server with an HTTP GET request.
Syntax:
$.get(URL,callback);
$("button").click(function(){
  $.get("demo_test.asp",function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});


  • jQuery $.post() Method
The $.post() method requests data from the server using an HTTP POST request.
Syntax:
$.post(URL,data,callback);
$("button").click(function(){
  $.post("demo_test_post.asp",
  {
    name:"Donald Duck",
    city:"Duckburg"
  },
  function(data,status){
    alert("Data: " + data + "\nStatus: " + status);
  });
});

There are many other popular JavaScript frameworks like: Angular, Backbone, Ember, Knockout, and more.


Basic Code Snippets
Get Text:
$("#btn1").click(function(){
  alert("Text: " + $("#test").text());
});

Set Text:
$("#btn1").click(function(){
  $("#test1").text("Hello world!");
});

Get Html:
$("#btn2").click(function(){
  alert("HTML: " + $("#test").html());
});

Set Html:
$("#btn2").click(function(){
  $("#test2").html("<b>Hello world!</b>");
});

Get Value:
$("#btn1").click(function(){
  alert("Value: " + $("#test").val());
});

Set Value: 
$("#btn3").click(function(){
  $("#test3").val("Dolly Duck");
});

Get Value:
$("button").click(function(){
  alert($("#w3s").attr("href"));
});

Set Value:
$("button").click(function(){
  $("#w3s").attr("href","http://www.w3schools.com/jquery");
});

$("button").click(function(){
  $("#w3s").attr({
    "href" : "http://www.w3schools.com/jquery",
    "title" : "W3Schools jQuery Tutorial"
  });
});


SQL Basics

Switch Case:
Following is the syntax of switch case in MySql.

Example:
Employee {
       id int,
       name string,
}


  • Employee table has 2 columns called as id and name. 
  • For ex, if you want string 'First' to be displayed for employee with id = 1 & 'Second' to be displayed for employee id = 2 then the query can be written as follows:

SELECT string,
CASE WHEN id = 1 THEN 'First' WHEN id = 2 THEN 'Second' END
From Employee

So every time id=1 is a part of result, it will display 'First'.

Indexing
Indexing could result in increasing the performance of the database. If indexes are not set then it impacts the performance. Here are some best practices of selecting the indexes:

  1. Pick a good clustering key: Not varchar but an int. 
  2. Int is narrow, stable, ever-increasing, and unique.
  3. An index can be added to any column that is being used as foreign key on other table.
  4. Avoid overlapping indexes. 
  5. Avoid indexing on too many columns. 
  6. Have a baseline number for testing. Before adding any columns your queries are taking 10 seconds to provide a response. Now after adding the indexes find out the time it takes to run the same queries. If its less then 10 seconds then you have added indexes on right columns. So observe, measure, and compare the baseline.

How to convert a string to a date: 
Its very common in business world to convert a string to a date for reporting purposes. To achieve those results here is an operation:
STR_TO_DATE('2003/07/09', 'yyyy/mm/dd')
Result: date value of July 9, 2003

Popular Sql Operations:

  1. COALESCE: Returns first non-null value from a list of strings. 
    1. Example 1: Select COALESCE(NULL, 'Interview questions', NULL, 'Product interview questions'); 
      1. Result: Interview questions
    2. Example 2: Select COALESCE(NULL, NULL, NULL, NULL, 'Interview', NULL, 'Product interview questions'); 
      1. Result: Interview
  2. CURRENT_TIMESTAMP: Returns current date and timestamp. "YYYY-MM-DD HH-MM-SS" format if used in a string context
    1. Example: Select CURRENT_TIMESTAMP
      1. Result: 2018-08-13 01:09:13

Spring Dependencies for Maven

<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelVersion>4.0.0</modelVersion>
    <groupId>com.practice.spring</groupId>
    <artifactId>SpringPractice</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>4.3.2.RELEASE</version>
        </dependency>
    </dependencies>

</project>

You might also like:









Servlet Filter

- Filter help to block a malicious request if they are not allowed to access a backend resource.
- Filter also help to manipulate the responses that will be sent back to the client.

Different types of filters:
  1. Authentication-Blocking: Block or allow any requests based on user identity.
  2. Logging and auditing: Helps in user tracking.
  3. Image conversion: Helps with scaling maps
  4. Data compression: Reduces download size
  5. Localization: Helps support the code in various countries based on different languages and formatting. 
  6. Encryption filters
  7. Tokenizing filters
  8. Mime-type chaining filters
  9. Caching filters
  10. XSL/T Filters: Helps transforming XML requests.

- Filters are specified in web.xml and are executed in the order specified in the file.
- Filter java class implements javax.servlet.Filter and implements these 3 methods: init(), doFilter(), destroy()

import javax.servlet.*;
import java.util.logging.Filter;

public class TestFilter implements Filter {
    public void  init(FilterConfig config) throws ServletException {
        //Get and print init param                
        String testParam = config.getInitParameter("param1");
        System.out.println("Test Param: " + testParam);
    }

    public void  doFilter(ServletRequest request,
                          ServletResponse response,
                          FilterChain chain)
            throws java.io.IOException, ServletException {

        // Get the method of the request
        String method = request.getMethod();
        logger.info("Request Method is: ", method);

        // Pass request back down the filter chain
        chain.doFilter(request,response);
    }
    public void destroy( ){
        //close any resources here        }
}

Compile TestFilter.java in usual way and put your class file in <Tomcat-installation-directory>/webapps/ROOT/WEB-INF/classes

Make following config change in the web.xml
<filter>
    <filter-name>TestFilter</filter-name>
    <filter-class>TestFilter</filter-class>
    <init-param>
        <param-name>param1</param-name>
        <param-value>Test</param-value>
    </init-param>
</filter>
<filter-mapping>
<filter-name>TestFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

The TestFilter will apply to all the servlets since we specified url-pattern as /*. For example if we want to apply TestFilter to only a class called as TestFile then the config will look like
<filter>
    <filter-name>TestFilter</filter-name>
    <filter-class>TestFilter</filter-class>
    <init-param>
        <param-name>param1</param-name>
        <param-value>Test</param-value>
    </init-param>
</filter>
<filter-mapping>
<filter-name>TestFilter</filter-name>
<url-pattern>TestFile</url-pattern>
</filter-mapping>

Multiple filters
<filter>
    <filter-name>TestFilter</filter-name>
    <filter-class>TestFilter</filter-class>
    <init-param>
        <param-name>param1</param-name>
        <param-value>Value1</param-value>
    </init-param>
</filter>

<filter-mapping>
<filter-name>TestFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<filter>
<filter-name>TestFilter2</filter-name>
<filter-class>TestFilter2</filter-class>
<init-param>
    <param-name>param</param-name>
    <param-value>Value</param-value>
</init-param>
</filter>

<filter-mapping>
<filter-name>TestFilter2</filter-name>
<url-pattern>TestFile</url-pattern>
</filter-mapping>
In this example, TestFilter will be applied followed by TestFilter2.

You might also like:
Java Concepts
Java String concepts
Immutable classes in Java
Remove duplicates from the array
Telephonic phone technical interview questions
Telephonic phone technical interview questions - Part 2
Serialization & Deserialization
Jersey Package Dependencies
Observable and Observer Interface
Servlet Client Request
Spring dependencies for Maven
Java String Operations

Mercurial Commands CheatSheet

Mercurial Commands:
  1. Merging
    1. hg update default
    2. hg pull
    3. hg update
    4. hg merge branch_name
    5. hg commit 
    6. hg push
  2. Creating a new branch
    1. hg branch branch_name
    2. hg commit -m “Creating a new branch” 
    3. hg push - - new-branch
  3. Post a review on one of the published reviews
    1. hg postreview -i {repositoryId} -e {CodeReviewId}
  4. To rollback a merge:
    1. hg update -C . 
  5. Clone a repository:
    1. hg clone ssh://merc//home/hg/RepoName
  6. Undo a merge:
    1. hg update -C -r .

Jersey Package dependencies

Dependencies:
Package: Server side support for Grizzly Containers
<dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-grizzly2-http</artifactId>
   <version>2.22.2</version>
</dependency>

Package: Server side support for JDK Containers
<dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-jdk-http</artifactId>
   <version>2.22.2</version>
</dependency>


Package: Server side support for Simple Containers
<dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-simple-http</artifactId>
   <version>2.22.2</version>
</dependency>

Package: Server side support for Jetty Containers
<dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-jetty-http</artifactId>
   <version>2.22.2</version>
</dependency>
<dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-jetty-servlet</artifactId>
   <version>2.22.2</version>
</dependency>

Package: Grizzly connector for Jersey Client
<dependency>
   <groupId>org.glassfish.jersey.connectors</groupId>
   <artifactId>jersey-grizzly-connector</artifactId>
   <version>2.22.2</version>
</dependency>
 

Package: Apache connector for Jersey Client
<dependency>
   <groupId>org.glassfish.jersey.connectors</groupId>
   <artifactId>jersey-apache-connector</artifactId>
   <version>2.22.2</version>
</dependency>

Package: Jetty connector for Jersey Client
<dependency>
   <groupId>org.glassfish.jersey.connectors</groupId>
   <artifactId>jersey-jetty-connector</artifactId>
   <version>2.22.2</version>
</dependency>


Package: Jersey
<dependency>
   <groupId>org.glassfish.jersey.containers</groupId>
   <artifactId>jersey-container-servlet</artifactId>
   <version>2.22.2</version>
   <scope>provided</scope>
</dependency>
<!-- if you are using Jersey client specific features without the server side -->
<dependency>
   <groupId>org.glassfish.jersey.core</groupId>
   <artifactId>jersey-client</artifactId>
   <version>2.22.2</version>
   <scope>provided</scope>
</dependency>

Package: JAX-RS API
<dependency>
   <groupId>javax.ws.rs</groupId>
   <artifactId>javax.ws.rs-api</artifactId>
   <version>2.0.1</version>
   <scope>provided</scope>
</dependency>

Apache Commons dependency
<!-- http://mvnrepository.com/artifact/org.apache.commons/commons-io -->
<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-io</artifactId>
    <version>1.3.2</version>
</dependency>


You might also like:
Java Concepts
Java String concepts
Immutable classes in Java
Remove duplicates from the array
Telephonic phone technical interview questions
Telephonic phone technical interview questions - Part 2
Serialization & Deserialization
Observable and Observer Interface
Servlet Filter
Servlet Client Request
Spring dependencies for Maven
Java String Operations

NoSQL

NoSQL Data models: key-value  Aggregate model.  key or id is used to get the data.  Lookup is based on the key.   document Aggre...