Uncategorized

5 Important rules to start with JavaScript

Sending
User Rating 5 (1 vote)

At first sight, JavaScript looks very simple language. But if you don't follow unobtrusive and OO pattern then you will treat it as one of the weird browser languages. But in today's world you can't make good websites without the help of JavaScript. Either you use Dojo, JQuery, ext js , moo tools or any JavaScript based plug-ins , you would require fair knowledge of JavaScript. Apart from keeping in mind while using  namespace, global and local variables. We should follow  these 5 simple rules (in no order and there can be many rules as per the programmer), we can improve JavaScript coding:

1. Do not make any assumptions about JavaScript features

Probably the most important feature of unobtrusive JavaScript is that you stop making assumptions:

  • You don't expect JavaScript to be available but make it a nice-to-have rather than a dependency
  • You don't expect browsers to support certain methods and have the correct properties but  test  them before you access them
  • You don't expect the correct HTML to be at your disposal, but check for it and do nothing when it is not available
  • You expect other scripts to try to interfere with your functionality and keep the scope of your scripts as secure as possible. use local variable and namespace properly

The first thing to consider before you even start planning your script is to look at the HTML code that you are going to enhance with scripting and see what you can use for your own purposes.

 2. Find your hooks and relationships (HTML, the base to build on)

Before you start your script look at the base that you build upon. If the HTML is unstructured , there is hardly any way to create a clever scripting solution

There are several things to consider in your HTML – hooks and relationships

 HTML Hooks

HTML hooks are first and foremost IDs, as these can be accessed with the fastest DOM method – getElementById. These are safe as IDs are unique in a valid HTML document (IE has a bug with name and ID, but good libraries work around that) and easy to test for.

Other hooks are HTML elements which can be read out with getElementsByTagName and CSS classes, which can not be read out with a native DOM method in most browsers (Mozilla will soon have one and Opera 9.5 already does though). However, there are a lot of helper methods that allow for a getElementsByClassName.

 HTML relationships

The other interesting thing about HTML is the relationships of your markup. Questions to ask yourself are:

  • How can I reach this element the easiest and with the least steps traversing the DOM?
  • What element do I need to alter to reach as many child elements that I need to change?
  • What attributes or information does a certain element have that I can use to link to another?

Traversing the DOM is expensive and can be slow, that is why it is a good idea to leave it to a technology that is already in use in browsers.

 3. Leave traversing to the experts (CSS, the faster DOM traveller)

It is pretty interesting that DOM scripting and traversing the DOM with its methods and properties (getElementsByTagName, nextSibling, previousSibling, parentNode and so on) appears as a confusing matter to a lot of people. It is interesting as we already do it with a different technology: CSS.

CSS is a technology that takes a CSS selector and traverses the DOM to access the desired elements and change their visual attributes. A rather complex JavaScript using DOM can be replaced with a single CSS selector:

var n = document.getElementById('nav');
if(n){
var as = n.getElementsByTagName('a');
if(as.length > 0){
for(var i=0;as[i];i++){
as[i].style.color = '#369'; as[i].style.textDecoration = 'none'; }
}
}

/* is the same as */

#nav a{ color:#369; text-decoration:none; }

 4. Understand Events (Event handling to initiate change)

Event handling is the next step to truly unobtrusive JavaScript. The point is not to make everything draggable and clickable or add inline handling. The point is to understand that Event Handling is true separation. We separate HTML, CSS and JavaScript but with Event Handling we go much further.

Elements in the document are there to wait for handlers to listen to a change happening to them. If that happens, the handlers retrieve a magical object (normally as a parameter called e) that tells them what happened to what and what can be done with it.

The really cool thing about most event handling is though that it does not only happen to the element you want to reach but also to all the elements above it in the DOM hierarchy (this does not apply to all events though – focus and blur don't do that). This allows you to assign one single event handler to for example a navigation list and use event handling's methods to reach what element was really involved. This technique is called event delegation and it has several benefits:

  • You only need to test if a single element exists, not each of them
  • You can dynamically add or remove new child elements without having to remove or add new handlers
  • You can react to the same event on different elements

The other thing to remember is that you can stop events from being reported to parent elements and you can override the default action HTML elements like links have. However, sometimes this is not a good idea, as browsers apply them for a reason. An example would be links pointing to in-page targets. Allowing for them to be followed makes sure that users can bookmark the state of your script.

 5. Work for the next developer (Making maintenance easier)

The last step to make your script truly unobtrusive is to give it another go-over when you finished and think about the next developer who has to take over from you once this went into production. Consider the following:

  • Are all the variable and function names logical and easy to understand?
  • Is the code logically structured? Can you "read" it from top to bottom?
  • Are the dependencies obvious?
  • Have you commented areas that might be confusing?

The most important bit is to understand that the HTML and CSS of a document is much more likely to change than the JavaScript (as these make up visual output). Therefore it is a great idea not to have any class and ID names or strings that will be shown to the end user buried somewhere in the code but separate it out into a configuration object instead.

myscript = function(){
   var config = {navigationID:'nav', visibleClass:'show'};
   var nav = document.getElementById(config.navigationID);
   function init(){
      show();
      if(nav.className === config.visibleClass){ reset(); } // do stuff
   }
   function show(){
     var c = nav.className; // do stuff
   }
   function reset(){
   // do stuff
   };
}();

That way maintainers know exactly where to change these without having to alter the rest of your code.

Source: http://icant.co.uk

Share your Thoughts