Simple Hovering Element w/ Triggering Element


/ Published in: JavaScript
Save to your folder(s)

added ability to use effects and some other improvements.


Copy this code and paste it in your HTML
  1. var HoverItem = Class.create({
  2. timeout: null,
  3. effect: null,
  4. open: false,
  5. enabled: true,
  6. initialize: function(item, trigger){
  7. this.item = $(item);
  8. if( !this.item ){
  9. throw 'HoverItem: invalid item';
  10. }
  11. if( !Object.isArray(trigger) ){
  12. trigger = [trigger];
  13. }
  14. this.triggers = trigger.map(function(e){ return $(e);}).compact();
  15. if( this.triggers.length === 0 ){
  16. throw 'HoverItem: no valid trigger element';
  17. }
  18. this.options = Object.extend({
  19. timeout: 0.5,
  20. align_to_trigger: true,
  21. zIndex: 100,
  22. effects: null
  23. }, arguments[2] || {});
  24. this.item.hide();
  25. if( this.options.align_to_trigger !== false ){
  26. var trigger_pos = this.triggers[this.options.align_to_trigger].positionedOffset();
  27. var trigger_dims = this.triggers[this.options.align_to_trigger].getDimensions();
  28. this.item.setStyle({position: 'absolute', top: trigger_pos.top + trigger_dims.height + 'px', left: trigger_pos.left + 'px', zIndex: this.options.zIndex});
  29. }
  30. [this.item].concat(this.triggers).invoke('observe', 'mouseleave', this.closeItem.bindAsEventListener(this))
  31. .invoke('observe', 'mouseenter', this.openItem.bindAsEventListener(this));
  32. },
  33. /* have to be careful with these because of timing issues */
  34. disable: function(){
  35. this.enabled = false;
  36. },
  37. enable: function(){
  38. this.enabled = true;
  39. },
  40. openItem: function(){
  41. console.log('openItem! ' + this.enabled);
  42. if( !this.enabled ){
  43. return;
  44. }
  45. this.stopClose();
  46. if (!this.open) {
  47. this.open = true;
  48. try {
  49. if (this.effect) {
  50. this.effect.cancel();
  51. }
  52. this.effect = new this.options.effects.open.effect(this.item, this.options.effects.open.options ||
  53. {});
  54. }
  55. catch (e) {
  56. this.item.show();
  57. }
  58. }
  59. },
  60. closeItem: function(){
  61. if (!this.timeout) {
  62. this.timeout = this._closeItem.bind(this).delay(this.options.timeout);
  63. }
  64. },
  65. _closeItem: function(){
  66. this.open = false;
  67. try{
  68. if( this.effect ){
  69. this.effect.cancel();
  70. }
  71. this.effect = new this.options.effects.close.effect(this.item, this.options.effects.close.options || {});
  72. }catch(e){
  73. this.effect = null;
  74. this.item.hide();
  75. }
  76. },
  77. stopClose: function(){
  78. if (this.timeout) {
  79. clearTimeout(this.timeout);
  80. this.timeout = null;
  81. }
  82. }
  83. });

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.