6/06/2014

“javascript:void(0)” Fires window.onbeforeunload in IE

When Building a single page web application, we frequently provide a link as a trigger to run JavaScript.
 <a href = "javascript: void(0);" onclick = "alert('hello');" >Link</a>
When user clicks on the link, IE will  fires window.onbeforeunload event, although the link doesn't attempt to redirect to other page. This may make user annoyed. There are two solutions for this issue.
The first one is:
 <a href = "#" onclick = "alert('hello');" >Link</a>
The other one is :
 <a href = "javascript:;" onclick = "alert('hello'); return false;" >Link</a>

The  second one is preferred, since it will not append an anchor in URL.

6/05/2014

[JS] Get Parameters in a JavaScript Script Tag

In google-code-prettify, you can specify the code language and skin just in one line. No extra configuration is necessary since the parameters is already appended to the URL.
<script src="svn/loader/run_prettify.js?lang=css&skin=sunburst"></script>
So how does the JS file know the parameters appended to its URL? You can just call the function getScriptParams(..) to get the parameters in JS object format.
This will get JS object:
console.log(getScriptParams('run_prettify.js')); 
Here is implementation of getScriptParams(..).
function getScriptParams(scriptFileName) {
   // Get all script tag
  var scripts = document.getElementsByTagName('script');
  var result = {};
  for(var i = 0; i < scripts.length; ++i) {
     // Check if the file name is the same as scriptFileName
    if(scripts[i].src.indexOf(scriptFileName) !== -1) {    
      // Get the parameters string     
      var urls = scripts[i].src.split('?');
      if(urls.length == 2) {
        var parameters = urls[1].split('&');        
        for(var j=0; j< parameters.length; ++j) {
          var pair = parameters[j].split('=');
          result[pair[0]] = pair[1];
        }
      }
      break;
    }
  }
  return result;
}