Posted By

pmw57 on 12/12/14


Tagged

javascript jquery hook


Versions (?)

jQuery hook for separation of concerns


 / Published in: jQuery
 

URL: http://www.sitepoint.com/effective-event-binding-jquery/

The purpose of this hook method is to help provide a separation of concerns between CSS and JavaScript.

Typically class names are used to attach JavaScript to HTML elements. Using a separate data-hook attribute helps to protect the scripting from CSS changes.

With the following example toggle button for a menu, we can hook on to the data-hook attribute.

Toggle Nav Menu

  1. // define hook method
  2. $.extend({
  3. hook: function (hookName) {
  4. var selector;
  5. if (!hookName || hookName === '*') {
  6. // select all data-hooks
  7. selector = '[data-hook]';
  8. } else {
  9. // select specific data-hook
  10. selector = '[data-hook~="' + hookName + '"]';
  11. }
  12. return $(selector);
  13. }
  14. });
  15.  
  16. // use hook method on data-hook attributes
  17. $.hook('nav-menu-toggle').on('click', function() {
  18. $.hook('nav-menu').toggle();
  19. });

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: Garcia15 on December 17, 2014

This is a big help for me as a newbie. Thanks! :)

You need to login to post a comment.