jQuery: performing per-page actions

jQuery allows us to perform many actions on web documents. However, sometimes we want to perform only certain actions on a given page. Given that we're actually working on DOM elements, an obvious approach would probably be to check whether an element exists or not:

var elementExists = function(element) {
    
        if(document.getElementById(element) !== null) {
 
     return true;
     
 } else {
 
     return false;
     
 }
    
    };

Here we're only testing a given string against the value of an ID attribute. But there's a catch: an ID element can actually occur on several pages, though it can't never occur on the same page. We must to refine our approach and we can fulfill our goal by taking into account an handy CSS practice used by developers: ID attributes on the body element. For example:

<body id="home">
...
</body>

By providing an ID attribute this way we're actually creating an unique reference to a given page. We can take advantage of this technique to perform per-page actions with jQuery:


var AClass = new function() {

    var self = this;
    
    /** @param {Object}
              @access Public
              @returns {Object} */

    this.execute = function(callback) {
        
 
 return callback.method(callback.parameters);
    };
    
    this.loader = function(page) {
    
        page = $(page).attr('id');
 
 return this.execute({
 
     parameters: page,
     method: function(parameters) {
         switch(parameters) {
      case 'home':
          // do something
          break;
      case 'articles':
      case 'blog':
          // do something
       break;
   case 'contacts':
       // do something
       break;
          
      default:
          break;
  }
     }
 });
    
    
    };



}();

function init() {
    AClass.loader('body');
}

$(document).ready(function() {
    init();
});

By doing so, we're actually performing different actions on different pages. Obviously you can improve the methods provided above.

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Leave a Reply

Note: Only a member of this blog may post a comment.