Showing posts with label JQuery. Show all posts
Showing posts with label JQuery. Show all posts

Sunday, October 18, 2015

Bootstrap - concepts

About bootstrap:

  • Uses HTML, CSS and Javascript
  • front-end framework
  • Easy and faster to use and develop 
  • Responsive design 
  • Mobile-first approach: In Bootstrap 3, mobile-first styles are part of the core framework 
  • Browser compatible 


Bootstrap concepts:


  1. Application setup with bootstrap 
    1. Reference to bootstrap
      1. Download - http://getbootstrap.com
      2. CDN - 
        1. CSS - http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css
        2. JavaScript - http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js
    2.  <!DOCTYPE html> at the beginning of the html page
    3. Mobile first settings - '' 
      1. Width is the width application should take to display
      2. initial-scale - initial zoom of the page
    4. Container - bootstrap requires a containing element to wrap site contents. There are two container classes to choose from - 
      1. .container - class provides a responsive fixed width container
      2. .container-fluid class provides a full width container
         
  2. Bootstrap Grid System - grid systems are used for creating page layouts through a series of rows and columns that host application content
    1. Rows must be placed within a .container class
    2. Content should be placed within the columns, and only columns may be the immediate children of rows
    3. Predefined grid classes
      1. .row
      2. .col-xs-<#> .col-sm-<#> .col-md-<#> .col-lg-<#> - # could be 1-12
    4. Multiple column classes can be used to support wide range of devices  
  3. Normalize - bootstrap uses Normalize to establish cross browser consistency in the default styling of HTML elements. Normalize.css is a modern, HTML5-ready alternative to CSS resets. CSS reset is to set styling to html elements to null thus avoiding cross-browser differences as much as possible
     
  4. Text emphasis - text-left text-center text-right text-muted text-primary text-success text-info text-warning text-danger.
     
  5. List - list-unstyled list-inline.
     
  6.  Bootstrap tables - 
    1. base table markup - table 
    2. Optional markups - table-striped table-bordered table-hover.(example) 
    3. Contextual classes - active success warning danger. (example)
    4. The .table-responsive class creates a responsive table. Put this class in a div which holds a table
       
  7. Bootstrap form layouts- 
    1. Types
      1. Vertical (default) form 
      2. In-line form 
      3. Horizontal form
    2. Rules to follow 
      1. improve accessibility - always use >form role="form"< 
      2. optimum spacing - wrap labels and form controls in >div class="form-group"< 
      3. class .form-control to all textual input, textarea and select elements
      4. For Horizontal form - 
        1. Add class .form-horizontal to the
          element 
        2. Add class .control-label to all
        3. Use grid classes to align labels and groups of form controls
    3. Example - includes all three type of forms  
  8. Alert - 
    1. Create an alert 
      1. Use .alert class in a div
      2. Followed by one of four contextual classes .alert-success, .alert-info, .alert-warning or .alert-danger.
    2. To add close functionality
      1. Add a link or button element in alert div
      2. add class="close" and data-dismiss="alert".
      3. Use × (×) HTML entity for close buttons
    3. Animated alert - add class fade in in alert div.
       
  9. Dropdown - (example)
    1. To create
      1. Mark a div with class="dropdown".
      2. Add a button or link to open dropdown menu with "class=dropdown-toggle" and data-target="dropdown".
      3. Add class="caret" in a span element to show dropdown arrow
      4. Add class="dropdown-menu".
    2. Dropdown divider - class="divider" in li element
    3. Dropdown header- class="dropdown-header" in li element
    4. Make it accessible to screen readers
      1. Add role="menu" and aria-labelledby="aName" in ul element
      2. Add role="presentation" in li element
      3. Add role="menuitem" in HTML element used inside li
  10. Panel
    1. Create with .panel class in a div
    2. need to define panel-header panel-body panel-footer
    3. Contextual classes - panel-default panel-success panel-info panel-danger panel-warning panel-primary.
    4. To group panels - panel-group.
  11. Collapsible
    1. On button or link
      1. Create a div with collapse class
      2. Create a link or button HTML element with data-toggle="collapse" and data-target="#div_id". This is to show/hide the collapsible div
    2. On a panel - (example)
      1. Add button or link in panel header (see above)
      2. Put panel body and footer in a div with classes panel-collapse collapse.
    3. Accordion - (example)
      1. Panel group div should be ided with a name
      2. Use the data-parent attribute to specify the div id - all collapsible elements under the specified parent will be closed when one of the collapsible item is shown
         
  12. Tabs
    1. Tabs are created with $gt;ul class="nav nav-tabs"<.
    2. Current page is marked using class="active" in li element
    3. Use dropdown creation structure in a li which needs to be displayed as dropdown and mark that li with class="dropdown". (example)
    4. dynamic tabs
      1. add the data-toggle="tab" attribute to each link
      2. add a .tab-pane class with a unique ID for every tab
      3. wrap them inside a div element with class .tab-content. 
    5. Pills - similar concept as tab. Most cases replacing tab with pill will work
  13. Modal - (example)
    1. Use a button or a link with attributes: 
      1. data-toggle="modal" opens the modal window 
      2. data-target="#id" points to the id of the modal
    2. Defining modal 
      1. The parent div of the modal must have an ID, will be used in data-target attribute and .modal class 
      2. The attribute role="dialog" to improve accessibility 
      3. The .modal-dialog class sets the proper width and margin of the modal. 
    3. Defining modal content
      1. A div with class="modal-content" 
      2. Add the modal's header .modal-header, body .modal-body, and footer .modal-footer. 
      3. To add close feature in header
        1. Add a button/link inside the header with data-dismiss="modal"
        2. Add .close class styles the close button
      4. Add .modal-title class styles the header with a proper line-height.
  14. Images - below classes need to use in img html element
    1. img-rounded img-thumnail img-circle img-responsive.
       
Note:
1. To learn about bootstrap elements which are not mentioned and know more in detail about the elements explained, see the resources



Resources:
1. http://www.w3schools.com/bootstrap/
2. http://www.tutorialspoint.com/bootstrap/

Saturday, October 17, 2015

JQuery - Handout - quick memory refresher

Introduction:
This post is to provide some quick refreshing facts and best practices for those folks who haven't worked on jQuery for a while. For beginners, it's better to go through the basic/advance tutorials first and check back with this later.

About jQuery:

1. jQuery is a JavaScript Library
2. jQuery greatly simplifies JavaScript programming


jQuery concepts:

  1. Pointing to jQuery
    • From local reference - ''- assuming jquery.js file is in same folder with the html
    • Content Delivery Network (CDN) based - 'src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js" type="text/javascript"'
       
  2. launching code - Option-02 is prepared as that's invoked as soon as the DOM is ready rather waiting the page loaded fully (including images)
    1. Option-01: window.onload = function() { //code};
    2. Option-02: $( document ).ready(function() { //code });
    3. Option-03: is shortcut to option-02. '$(function(){ //code});'
       
  3. Callbacks and functions - A callback is a function that is passed as argument to another function and will be executed only after the function where it's passed has completed
    1. Callback without Arguments - '$.get('aPage.html', callBackFn);'
    2. Callback with Arguments - 
      1. Not possible - '$.get('aPage.html', callBackFn(param1, param2));'. This will execute the callBackFn first and return of it will be passed to get function
      2. Correct way - '$.get( "aPage.html", function() { callBackFn( param1, param2 ); });'
         
  4. $ vs $()
    1. Methods called on jQuery selections (used $()) are in the $.fn namespace, and automatically receive and return the selection as this
    2. Methods in the $ namespace are generally utility-type methods, and do not work with selections; they are not automatically passed any arguments
        
  5. Ways to avoid conflict with other libraries
    1. new alias - noConflict returns a reference to jQuery function
      'var $j = jQuery.noConflict();'
    2. use self invoking function -
      'jQuery.noConflict();(function($){ //code})(jQuery);'
    3. Argument through jQuery(document).ready() function
      'jQuery(document).ready(function( $ ) { // code });'
       
  6. Selecting elements
    1. by 
      1. tag name - '$("aDOM");'
      2. ID - '$("#idToFind");'
      3. class name - '$(".className");'
    2. Pseudo selectors - :visible :enabled :checked :text :button :file (see references for complete list)
    3. comma to use to select multiple DOM objects
    4. chaining - any method call on a selection returning a jQuery object, allows to call jQuery method on the object without pausing for a semicolon.
      '("#aDiv").find("p").eq("1").html("Changed text");' - find second p in a dive called aDiv and change content
       
  7. Methods - 
    1. getter/setter - html, text, val - can be both setter (with argument) or getter (no argument) 
    2. Move, copy and remove elements
    3. Attributes - .attr() to get/set value to selector's attribute.
      1. Object of key-value pair can be passed to set multiple
         
  8. Selection traversing
    1. parents - .parent() .parents() .parentUntil() .closest(). 
    2. children - .children() .find().
    3. Siblings - .prev() .next() .siblings() .nextAll() .prevAll() .nextUnti() .prevUntil()
    4. Styling and dimensions
    5. CSS classes - addClass("aClass") removeClass("aClass").
    6. Dimensions - width, height - getter/setter
        
  9. Data methods - stores data to the element and manages the memory issues.
    '$("#aDiv").data("aKey", {name:"Riaz"});' '$("#aDiv").data("aKey");'
      
  10. Utility methods - 
    1. $.trim() - 
    2. $.each() - generic iterator function for looping over object/arrays/ array-like objects
      example:
      '$.each([1,2,3,4], function(idx, val){ console.log("Element "+idx + " is "+val);});'
      output:
      Element 0 is 1
      Element 1 is 2
      Element 2 is 3
      Element 3 is 4
       
    3. $.proxy(function, scopeObj) -
      example:
      var aFn = function() { console.log( this ); };
      var aObj = { name: "Riaz" };
      aFn();
      var proxyAFn = $.proxy( aFn, aObj );
      myProxyFunction();

      Output:
      Window {external: Object, chrome: Object, document: document, speechSynthesis: SpeechSynthesis, caches: CacheStorage…}
      Object {name: "Riaz"}
       
    4. $.type() - returns the type of passed object
    5. .map() - returns array from matched elements from selector
        
  11. jQuery events - 
    1. Some common events
    2. Mouse Event Key Event Form Event window Event
      click keypress submit load
      dblclick keydown change unload
      mouseenter keyup focus size
      mouseleave    blur scroll
    • Event call syntax - 
      • Assign an event - $("p").click();
      • Indicates what should happen after event -
        $("p").click(function(){ /*actions*/});
    • Usage of '.on()'. 
      • All the methods above are shortcut of this
      • Syntax - '$("p").on("click", function(){/*actions*/});'
    • Handling event - 
      • Many events single event handler - comma separated events
      • Multiple event and event handler association -'$( "p" ).on({ "click": function() { console.log( "clicked!" ); },
        "mouseover": function() { console.log( "hovered!" ); } });
        '
      • Data can be passed to event -
        '.on( "click", {name:"Riaz"}, function(event){ console.log("Name:"+event.data.name");});'
    • Instead of anonymous function, a named function can be passed as event handler 
    • Namespacing event - for complex and plugin application, it's a good idea to namespace application specific events to avoid conflict 
    • tead down events
      • Unbind all click event - $( "p" ).off( "click" ); 
      • Unbind only aHandler from click - $( "p" ).off( "click", aHandler );
    • Event handler to run only once - using '.one(...)'
    • Properties and method of eventhanlder
      • Properties - pageX pageY which type data target namespace timestamp etc.
      • Methods - preventDefault() stopPropagation() etc
12. Ajax in jQuery
  • Syntax - '$.ajax(...)'
  • Data types - type of data you expect to get back from an Ajax request
    • text html script json jsonp xml
  • API -
    // Using the core $.ajax() method
    $.ajax({
    // The URL for the request
    url: "- page url",
    // The data to send (will be converted to a query string)
    data: {  },
    // Whether this is a POST or GET request
    type: "GET",
    // The type of data we expect back
    dataType : "json",
    // Code to run if the request succeeds;
    success: function( json ) { /* do something */ },
    // Code to run if fails; raw request and status codes are passed
    error: function( xhr, status, errorThrown ) { /* do something */ },
    // Code to run regardless of success or failure
    complete: function( xhr, status ) { /* do something */ } });
  • Convenient functions - below functions are wrapper around core .ajax()
    • functions - $.get $.post $.getScript $.getJSON
    • parameters - 
      • Required - url
      • Optional - data success dataType
  • Ajax events
    • Local events - specify within ajax request object
      • beforeSend success error complete
    • Global events
      • ajaxtStart ajaxStop
13. Serializing form data
  • Using $("#aForm").serialize() - serializes form data into a query string
  • Using  $("#aForm").serializeArray() - serializes to array of objects

Resources:
1. http://api.jquery.com/
2. http://www.w3schools.com/jquery/
3. https://learn.jquery.com/

    Wednesday, May 23, 2012

    JQuery - Best Practices

    Best practices:
    1. Save selection in a variable if the selection needs to make multiple time.
      Explanation:  jQuery doesn't do caching of selections and for every selection lot of code runs behind the scene
    2. Use 'if($("element").length)' instead of  'if($("element"))' to make sure selection has records
      Explanation:  Any selection using $() always returns an object and object always evaluates to TRUE, even if selection doesn't contain any elements.
      'if($("element"))' will return '[]' which is treated as empty object