Best Practices of Javscript

Best Practices for Javascript Coding

Inclusion of Code

  • Use external JavaScript files. Do NOT include JavaScript in-line in the page unless there is a good reason.
  • Use the <script> tag to include your JavaScript files at the bottom of your HTML document just before the closing </body> tag. For optimal page performance, concatenate your JavaScript into separate file.

Formatting of Javascript Code

  • Open braces are preceded by a single space.
  • Open braces should appear on the same line as their preceding argument.
  • Close braces should appear at the same indentation as the statement preceding the opening brace.
  • There should be no space characters between parentheses and their contents.
  • Use semicolons and do not rely on automatic semicolon insertion.
  • Each comma and colon (and semi-colons that don’t end a line) should be followed by a single space.

Variable declaration

To avoid confusion between global and local variables, we declare each variable on its own line with the var keyword. We do not use a single var keyword and then chain several variable declarations onto it separated by a comma.

Variable Names and Types

  • Variable names should be Camel Case.
  • Objects, classes, and name-spaces should be Title Case.
  • Boolean values should be prefixed with is if at all possible.
    Cached JQuery objects can be prefixed with $.
  • Use shorthand versions of empty Arrays and Objects.

Examples:

// some examples
var exampleValue ='my example variable value';
var numberOfTimes =3;
// booleans
var isThisWorking =true;
var isNotWorking =0;
// cache a selector
var $body =$('body');
// short hand objects and arrays
var newObject ={};
var newArray =[];

Limit Events — Use Event Delegation

With jQuery this is easy, simply use the on method with a selector:


$('body').on('click','a.scroller',function(){
// this only runs if the a.scroller is matched
});

Too many events bound on a page can mean memory leaks or just an accumulation of handlers bound to DOM elements which becomes less and less efficient over time.

Additionally, event delegation has the added benefit of persisting events over dynamic page updates when items are added or removed from the DOM.

More code practices

  • Avoid using document.write.
  • Only run scripts on a page that are needed for that page.
  • Don’t repeat yourself (i.e. keep your code DRY)
  • Do not modify JavaScript core objects .prototype unless you really know what you’re doing.
  • Use method names that make sense, such as init() or setup() for code that starts things off. Be consistent on your project.
  • Binary and ternary operators should have a single space on each side.
  • Quoted values should be in ‘single quotes’ so that double quotes may easily exist inside them.
  • Comment JavaScript code thoroughly and consider using a pattern such as those described by JSDocs so that documentation may be generated automatically.
  • Conditional statements go on a new line followed by the opening brace. Else/else go on the same line as the brace.
  • Use type strict checks with === as opposed to == whenever possible.
Continue Reading

Code Standards and Best Practices for Front End Development

Coding Standards for Front End Development

Three pillars of front end development:

  • Semantic HyperText Markup Language (HTML) for structure
  • Cascading Style Sheets (CSS) for presentation
  • JavaScript (JS) for behavior and interaction

General Standards

While we are writing code that must reach a desired goal, must be read and understand by others.

Code Consistency.

Usage of the same patterns is critical between team members so as to never cause confusion.

Indentation

  • Please consistently indent, nest, include braces, quotes, and new lines so that code is clear and can be read easily.
  • New code that is added should never deviate from existing formatting conventions or change the indent levels.
  • For all code languages, we recommend the use soft tabs comprised of four spaces per tab. Hitting the Tab key in your text editor should generate four space characters rather than one tab character. This results in our code appearing identical across platforms.
  • If tab stops are favored by a team, simply maintain consistency for a project and it’s deliverable. so developers can make adjustments to their editing environments a single time.

Readability

  • We encourage liberal use of white-space, comments, and descriptive variable names as appropriate for writing easy-to-read code.
  • The ability for another developer to read a code is essential.
  • No need to think about compressed way of code writing while you developing application, we will use automated server side or other build process to optimize files. This includes concatenating files, code minification, gzipping and more.

Areas of critical consistency include:

  • Code formatting
  • Naming conventions
  • File and folder structure
  • Examples or sample code
  • How page components might be broken down or re-used

Points to remember when lookup the UX designs:

  • Templates and types of pages.
  • Which sections of pages (i.e. components) are reused.
  • Type of Frameworks
  • CSS grid systems (LESS, SASS or Custom).
  • Server-Side delivery platforms.

Performance Caveats

In some cases for performance reasons it may be good practice to in-line critical styles in a style block in the document’s head.

This delivers these styles to the browser in the fastest method possible by preventing the need for an additional HTTP request.

CSS Deliverables

Delivered CSS should be concatenated, minified, tested against browser bugs (e.g. MSIE selector count bugs) and extra files should be removed.

File naming conventions should be consistent and language or use-case specific files should be clear and not be easily confused with the global style CSS.

Our CSS should be concerned the below points:

  • Browser Compatibility
  • Media Queries
  • Accessibility and CSS
  • CSS pre-processors usage
  • Internet Explorer or browser-specific bugs
  • Usage of CSS3 transitions, transforms, and more
  • Vendor prefixes
  • Color Management

Best Practices for Front End Development

Click the respective link for the detail view of best practices.

Continue Reading

When scroll down change the header position to be fixed.

When scroll down change the header position properties


 function init() {
    window.addEventListener('scroll', function(e) {
        var distanceY = window.pageYOffset || document.documentElement.scrollTop,
        shrinkOn = 100,
        header = document.querySelector("header");
        if (distanceY > shrinkOn) {
            classie.add(header,"smaller"); // add class name when page scrolls
        } else {
            if (classie.has(header,"smaller")) {
                classie.remove(header,"smaller");
            }
        }
    });
}
window.onload = init();

Explanation:
When we scroll down, class smaller will add in header element. So, we can set the position: fixed property to smaller class. Otherwise smaller class will be removed.

Continue Reading

Browser feature detection using Modernizr

Browser feature detection using Modernizr Plugin

Before discussing about runtime approach using modernizr, we will see couple of browser based approach.

  • Caniuse.com
  • Html5test.com

These websites are useful to identify the browser supports for HTML5 features and related specifications.

Modernizr

Modernizr is ajavascript library. It detects either user browser is supporting HTML and CSS3 features or not. It is very useful to detecting HTML5 and CSS3 features Using this feature detection support, developers can try some alternative approaches to implement the same kind of feature in that unsupported browsers.

First we should embed the Modernizr js file in head section.


<script src="modernizr.js"></script>

To check video feature support in different browsers, we can use the following script.


//Example 1:
if(Modernizr.video == false)
{
//alert("Browser doesn't support HTML5 Video");
}

//Example 2:
To check camvas feature support in different browsers, we can use the following script.
if("geolocation" in navigator) {
  navigator.geolocation.getCurrentPosition(function(position) {
    // show the location on a map by using the Google Maps API
  });
} else {
  // showing static map image
}


Continue Reading

Drag and Drop feature using HTML5 API

Drag and Drop feature implementation

We should use html event attributes like ondragover, ondrop and ondragstart to achieve drag and drop feature.

HTML5:


<div draggable = "false">
<!-- ondragover event: Specifies where the dragged data can be dropped -->
<!-- ondrop event: When the dragged data is dropped, a drop event occurs -->
<div id="div1" 
             style="width: 300px; height: 300px; padding: 10px; border: 1px solid #FF4500;"
             ondragover="allowDrop(event)" 
             ondrop="drop(event)"
             draggable = "false">
</div>
<!--ondragstart = Specify what should happen when the element is dragged -->
<img 
             id="drag1" src="HTML5.jpg" 
             draggable="true" 
             ondragstart="drag(event)" 
    width="204" height="204" />
</div>

Script:


        function drag(event){
         // set the target element
            event.dataTransfer.setData("ControlID", event.target.id); 
        }
        function allowDrop(event){
            //To allow a drop, we must prevent the default handling of the element
            event.preventDefault();
        }
        function drop(event){
            //To allow a drop, we must prevent the default handling of the element
        event.preventDefault();
         // append drag element in to drop area
            var controlId = event.dataTransfer.getData("ControlID");
            event.target.appendChild(document.getElementById(controlId));
        }

Explanation:

  • ondragover event: It specifies when an element is dragged over a drop target.
  • ondrop event: When the dragged data is dropped, a drop event occurs.
  • Ondragstart: It specify what should happen when the element is dragged.
  • event.preventDefault() – Prevent the default behavior of an element.
Continue Reading

What are the steps to learn front end web development?

Learning Front End Development

  • First learn about web development basic concepts such as domain, web hosting, web server, FTP, HTTP, HTTPS, markup languages, script languages, SEO, version control, responsiveness, recent trends in web development… ect
  • Then focus on creating structures (image, title, table, logo, content section, slider, tab.. ect) using markup language like HTML/HTML5.
  • Then applying styles (color, fonts, background, line-height, border.. etc) for created structures using CSS/CSS3.
  • Create interaction between the webpage and user by using scripts like Javascript and Jquery.
  • Try to create responsive web page by using media queries.
  • Then use advanced responsive framework like Bootstrap and Foundation.
  • Learn Advance Javascipt based libraries such as Angular JS, React JS, Ember JS, Knockout JS, Node JS for advanced web development.
Continue Reading