so i've been trying organize jquery code (which has in $(document).ready()
) implementing object literal on #menu
. event delegation used work no longer working.
html
<div id="menu"> <header id="menu-header"> <button id="menu-button" type="button" class="btn btn-default btn-lg button-menu" aria-label="menu"> <span class="glyphicon glyphicon-menu-hamburger" aria-hidden="true"></span> <h1>problems</h1> </button> </header> ... </div>
jquery
$(document).ready(function () { menu.init(); ... }); var menu = { $menu: $('#menu'), $menubutton: $('#menu-button'), init: function () { this.$menubutton.on('mouseenter', function () { this.$menubutton.children('.glyphicon-menu-hamburger').hide(); this.$menubutton.children('h1').fadein(200); }); this.$menubutton.on('mouseleave', function () { this.$menubutton.children('h1').hide(); this.$menubutton.children('.glyphicon-menu-hamburger').fadein(200); console.log("is working"); }); console.log("menu init being called"); } };
and while menu init being called
being printed, other print statement doesn't show up, feel indicates .on()
not being initialized correctly.
i feel may making selector typo or something, can't seem figure out.
if me appreciated!
this
within callbacks doesn't point menu
. points dom nodes fired event.
if want callbacks executed in context of object, should use $.proxy
:
...on('mouseenter', $.proxy(function () { ...code... }, this));
additionally, if execute $('#menu')
or other jquery selector before dom nodes exist on page, objects return empty collections.
initialize data after dom ready, or query dom part of callbacks.
Comments
Post a Comment