I am trying to add a class to an instance of a subclass of goog.ui.Button
when the user hovers over the button.
To this end, I overrode handleMouseOver
:
/**
* Handles mouseover events.
* @param {goog.events.BrowserEvent} e Mouse event to handle.
* @override
*/
myapp.ui.Button.prototype.handleMouseOver = function(e) {
goog.base(this, 'handleMouseOver', e);
goog.dom.classes.add(this.getElement(), 'button-hover-state');
};
However, when I hover over the button, the class 'button-hover-state' is not added to the button. Why not? Chrome Console is not issuing any errors or warnings.
I could listen to an event and respond instead of overriding handleMouseOver
, but shouldn't overriding this function alter what happens when the mouse enters the element?
The reason why your method myapp.ui.Button.prototype.handleMouseOver
does not do anything is because mouse events are not being dispatched.
The default renderer used by goog.ui.Button
is goog.ui.NativeButtonRenderer
. The method goog.ui.NativeButtonRenderer.prototype.createDom
calls goog.ui.NativeButtonRenderer.prototype.setUpNativeButton_
, which in turn, calls:
button.setHandleMouseEvents(false);
There are couple of approaches you could use to enable mouse events.
goog.ui.Component.prototype.render
/**
* Renders the button.
*
* @param {Element=} opt_parentElement Optional parent element to render the
* component into.
* @override
*/
myapp.ui.Button.prototype.render = function(opt_parentElement) {
goog.base(this, 'render', opt_parentElement);
this.setHandleMouseEvents(true);
};
goog.ui.ButtonRenderer
/**
* My custom button.
*
* @param {goog.ui.ControlContent} content Text caption or existing DOM
* structure to display as the button's caption.
* @param {goog.ui.ButtonRenderer=} opt_renderer Renderer used to render or
* decorate the button; defaults to {@link goog.ui.NativeButtonRenderer}.
* @param {goog.dom.DomHelper=} opt_domHelper Optional DOM hepler, used for
* document interaction.
* @constructor
*/
myapp.ui.Button = function(content, opt_renderer, opt_domHelper) {
goog.base(this, content,
opt_renderer || goog.ui.ButtonRenderer.getInstance(), opt_domHelper);
};
goog.inherits(myapp.ui.Button, goog.ui.Button);
When using goog.ui.ButtonRenderer
, the CSS class goog-button-hover
is automatically added to the button when the mouse hovers over the button and removed when the mouse leaves the button.