In JavaScript you can trigger an event by simply invoking the method on the element itself:
<input id="foo" type="text" onclick="console.log('Click event triggered');" />
var elem = document.getElementById('foo');
elem.onclick();
This works fine, as can be seen in this JSFiddle demo.
Polymer however has a different syntax, and uses on-click
instead of onclick
:
<input type="text" on-click="{{ clickEvent }}" />
Polymer('my-element', {
clickEvent: function() {
console.log('Click event triggered.');
}
});
I want to manually call the on-click
event on my input
element every time a key is pressed. For this I'm using an on-keypress
handler which fires my doClick
event:
<input type="text" on-click="{{ clickEvent }}" on-keypress="{{ doClick }}" />
doClick: function(event, detail, sender) {
console.log('Keypress event triggered.');
sender.onclick();
}
As per Polymer's event binding, sender
here is the element which the event occurred on (my input
element in this case). This unfortunately gives me the following output:
Keypress event triggered
Uncaught TypeError: object is not a function
The error happens because sender.onclick
is null
, as can be seen (on Chrome only) in this JSFiddle demo*.
How can I trigger an event on an element in Polymer?
* I've pinched the Polymer set-up from someone else's JSFiddle demo. This for whatever reason is only working in Chrome, however this problem isn't specific to Chrome itself.
Before anyone asks me why on earth I'd want to trigger the click event on an input
element every time a key is pressed, do note that this is nothing more than really crude example and not the actual code I'm using. This was just the shortest way I was able to demonstrate the problem.
The correct way to trigger a click event is calling click()
instead of onclick()
, so the correct function would be
doClick: function(event, detail, sender) {
console.log('Keypress event triggered');
sender.click();
}
here is the JSFiddle Demo
You can also call the function instead of triggering an event if you are pointing the same element
Polymer('my-element', {
clickEvent: function() {
console.log('Click event triggered');
},
doClick: function(event, detail, sender) {
console.log('Keypress event triggered');
this.clickEvent();
}
});
here is another JSFiddle Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With