Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle a hover the Polymer way without external libraries?

I figured I would need to do something like:

<li on-mouseover="{{ myHoverHandler }}">blah</li> because handling clicks looks like this:

<li on-click="{{ myClickHandler }}">blah</li>

I've tried using the way shown in the documentation here: declarative event mapping , but on-mouseenter and on-mouseover aren't working as expected.

I'm also having trouble passing parameters to my handlers, but that's a different story.

like image 354
edhedges Avatar asked Jul 14 '14 18:07

edhedges


3 Answers

on-mouseover and on-mouseout are correct, here's a demo as a Stack Snippet:

<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.3.3/platform.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/polymer/0.3.3/polymer.js"></script>

<my-app></my-app>
  
<polymer-element name='my-app'>
  <template>
    <button on-mouseover='{{onHovered}}' 
            on-mouseout='{{onUnhovered}}'>
      A humble button
    </button>
    <div>
      hovered: {{hovered}}
    </div>
  </template>
  <script>
    Polymer('my-app', {
      hovered: false,
      onHovered: function() {
        this.hovered = true;
      },
      onUnhovered: function() {
        this.hovered = false;
      }
    })
  </script>
</polymer-element>

It's possible that your element doesn't have a myHoverHandler property. Perhaps there's a typo?

As for whether to use Polymer event binding vs other methods, you can absolutely do this with vanilla js or jquery or whatever. Polymer handles a bit of the busy work, like making sure that the event handler is registered in conditional and repeated templates, binding this to the element which is usually what you want, and deregistering the handlers when their elements are removed from the DOM. There are times though when doing it manually makes sense too though.

like image 137
Peter Burns Avatar answered Nov 04 '22 16:11

Peter Burns


Actually it should be

<button on-mouseover='onHovered' 
        on-mouseout='onUnhovered'>

without the curly braces. Also, you don't need to pass in the properties if you need to use them in the event handler function.

like image 22
bigpotato Avatar answered Nov 04 '22 16:11

bigpotato


In case you need to react to hover on the host-Component itself, you should use listeners:

<dom-module id="hoverable-component">
  <template>

    <div>Hoverable Component</div>

  </template>

  <script>
    Polymer({
      is: 'hoverable-component',

      listeners: {
        mouseover: '_onHostHover',
        mouseout: '_onHostUnhover',
      },

      _onHostHover: function(e){
        console.debug('hover');  
      },

      _onHostUnhover: function(e){
        console.debug('unhover');  
      },

    });
  </script>
</dom-module>
like image 1
felvhage Avatar answered Nov 04 '22 17:11

felvhage