Is there an easy way to enable hitting enter to execute some javascript for a form with paper-input's. I can catch the keystroke on enter for every element but this seems kind of tedious.
With the current Polymer version 1.0 I was able to resolve that using iron-a11y-keys.
Here is an example bound to the whole form which triggers submission on any child input element:
<iron-a11y-keys id="a11y" target="[[_form]]" keys="enter"
on-keys-pressed="submitForm"></iron-a11y-keys>
<form is="iron-form" id="form"
method="post"
action="{{url}}">
...
Polymer({
is: 'example-form',
properties: {
_form: {
type: Object,
value: function() {
return this.$.form;
}
}
},
submitForm: function() {
document.getElementById('form').submit();
},
Currently (Polymer 0.3.4) there seems to be no event fired when one presses the enter key in a paper-input. But you can extend the paper-input element and add this functionality (see Extending other elements in the Polymer doc):
<polymer-element name="my-paper-input" extends="paper-input">
<template>
<shadow></shadow>
</template>
...
</polymer-element>
Then you can fire a custom event when the return key is pressed:
ready: function() {
self = this;
this.$.input.addEventListener('keypress', function(e) {
if (e.keyCode == 13) {
self.async(function() {
self.fire('enter', self.value);
});
}
});
}
For convenience the input value is passed to the event handler. Now you can use your new element like so:
<my-paper-input ... on-enter="{{inputEntered}}"></my-paper-input>
Edit 1:
Since the event bubbles up in the element hierarchy, one can catch it on the surrounding form element:
<my-form on-enter="{{anyInputEntered}}" ...>
Then one gets the events of all input elements in one place (the event propagation can be stopped by calling stopPropagation(); on the event object).
Edit 2:
It's best to give custom events unique names, so that they don't clash with the names of core events that may be added in the future (e.g. my-unique-prefix-input-entered).
Related
I have a Polymer 1.0 iron-pages element containing two custom elements:
<iron-pages selected="...">
<my-page>A</my-page>
<my-page>B</my-page>
</iron-pages>
I would like to take some action, like fetching ajax content, in my-page component, when the page becomes selected. How can I do this?
I came up with some ideas:
create a third component containing the iron-pages and wiring the events
<dom-module id="my-controller">
<template>
<iron-pages selected="..." on-selected-changed="onPageChanged">
...
<script>Polymer({...
...
onPageChanged:function(){
var page = ...;
page.selected = true;
}
and
<dom-module id="my-page">
...
onSelected:function(){
// fetch data
}
seems being rather much of an overhead to me, is this really necessary?
use <iron-pages selectedAttribute="..." ...>
but I could not find a way to detect the attribute change in <my-page>
Are there common patterns to solve this?
My solution was similar to your option A, but using events instead of method calls - its a more correct approach, and I'm actually baffled why Polymer's ironSelectableBehavior didn't implement it directly:
<iron-pages id="pages" ...>
<my-first-page></my-first-page>
<my-second-page></my-second-page>
</iron-pages>
...
<script>
Polymer({
is: 'my-app',
listeners: {
'pages.iron-select': 'pageSelected',
'pages.iron-deselect': 'pageDeselected'
},
pageSelected: function(e) { e.detail.item.fire('iron-select'); },
pageDeselected: function(e) { e.detail.item.fire('iron-deselect'); })
});
</script>
Then, in your element, listen for these events:
Polymer({
is: 'my-custom-element',
listeners: {
'iron-select': '_refreshData'
},
_refreshData: function(e) {
// load some data
}
});
Option B should also work - you probably need to set up the correct property and put an observer on it. In your component that contains iron-pages set up the attribute using the hyphenated form:
<iron-pages selected-attribute="activated" ...>
<my-first-page></my-first-page>
<my-second-page></my-second-page>
</iron-pages>
Then in your custom component set up the property and the observer:
Polymer({
is: 'my-first-page',
properties: {
activated: {
type: Boolean,
observer: '_activationChanged'
}
},
_activationChanged: function(newval, oldval) {
if (newval) // == true
console.log("just activated");
}
});
<iron-pages selected-attribute="visible"></iron-pages>
class MyClass extends PolymerElement {
get activePage() {
return this.shadowRoot.querySelector('iron-pages > *[visible]');
}
}
(sorry for the zombie thread, but came looking for this).
Using angularjs, I'm showing a 2-level list like this
- first main item
- first subitem of the first main item
- second subitem of the first main item
- AN EMPTY ITEM AS PLACEHOLDER TO ENTER THE NEXT SUBITEM
- second main item
- first subitem of the second main item
- second subitem of the second main item
- AN EMPTY ITEM AS PLACEHOLDER TO ENTER THE NEXT SUBITEM
In order to save place, I'd like to show the PLACEHOLDER only if anything in the corresponding div has focus, so that there's only one such placeholder. I know that there's ngFocus, but I'd prefer something simpler than creating tons of event handlers. Maybe something like this :
<div ng-focus-model="mainItem.hasFocus" ng-repeat="mainItem in list">
... main item line
... all subitems
</div>
A unidirectional binding would be sufficient as I don't need to set the focus.
The problem here is the following; we want to avoid adding event listener to each and every child, but add it only to the parent. The parent will be responsible for taking the appropriate action. The general solution to this, is to use even propagation (delegation). We attach only one listener to the parent, when an event occurs on the child (focus on input element in this example), it will bubble up to the parent and the parent will execute the listener.
Here's the directive:
app.directive('ngFocusModel', function () {
return function (scope, element) {
var focusListener = function () {
scope.hasFocus = true;
scope.$digest();
};
var blurListener = function () {
scope.hasFocus = false;
scope.$digest();
};
element[0].addEventListener('focus', focusListener, true);
element[0].addEventListener('blur', blurListener, true);
};
});
The directive listens for events and accordingly sets the value on scope, so we can make conditional changes.
There are several things to notice here.
focus and blur events don't "bubble", we need to use "event capturing" to catch them. That's why element.on('focus/blur') is not used (it doesn't allow for capture, afaik) but an addEventListener method. This method allows us to specify if the listener will be executed on "event bubbling" or "event capturing" by setting the third argument to false or true accordingly.
We could have used focusin and focusout events which "bubble", unfortunatelly these aren't supported in Firefox (focusin and focusout).
Here's a plunker with the implementation.
Update:
It occurred to me that this can be done with pure CSS using the :focus pseudo-class, the only downside is that the placeholder needs to be in proper position (sibling) relative to the input elements. See codepen.
Unfortunately the only rock solid way to do what you want is to respond to the focus\blur events on the inputs...that's the only way to get notified.
You could put a hidden input as the first element in each div and put the NgFocus attribute on it but that only works if a user tabs into it.
DEMO
I created a small directive that can be used for what you need:
app.directive('childFocus', function($window){
var registered = [];
// observing focus events in single place
$window.addEventListener('focus', function(event){
registered.forEach(function(element){
if(element.contains(event.target)){
// if element with focus is a descendant of the
// element with our directive then action is triggered
element._scope.$apply(element._scope.action);
}
});
}, true)
return {
scope : {
action : '&childFocus' // you can pass whatever expression here
},
link : function(scope, element){
// keep track ref to scope object
element[0]._scope = scope;
// (probably better would be to register
// scope with attached element)
registered.push(element[0]);
scope.$on('destroy', function(){
registered.splice(registered.indexOf(element[0]),1);
});
}
}
});
You could use the focus event of the '.parent *' selector to capture any focus events, then loop through each of the parent DIVs and use the :focus JQuery selector to check for child elements with focus, then add a class to the parent DIV and use that class to show/hide the placholder (see this jsfiddle):
$(function(){
$('.parent *').focus(function(){
$('.selected').removeClass('selected');
$('.parent').each(function(index, el){
(function($el){
setTimeout(function(){
console.log($el.attr('id'));
if($el.find(':focus').length){
$el.addClass('selected');
}
});
})($(el));
});
});
});
.parent{
padding:1rem;
margin:1rem;
border:solid 1px green;
}
.selected{
border:solid 1px red;
}
.parent .placeholder{
display:none;
}
.parent.selected .placeholder{
display:block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class='parent' id='div1'>
<input type="text" />
<div class='placeholder'>Placeholder</div>
</div>
<div class='parent' id='div2'>
<input type="text" />
<div class='placeholder'>Placeholder</div>
</div>
<div class='parent' id='div3'>
<input type="text" />
<div class='placeholder'>Placeholder</div>
</div>
<div class='parent' id='div4'>
<input type="text" />
<div class='placeholder'>Placeholder</div>
</div>
I have a directive where I am trying to bind the keypress and keydown events but for some reason they will not register.
element.bind("keydown keypress", function (event) {
console.log("here");
});
Any clues why this could be ?
If you look at the file selectMe.js in this plnkr you can see the binding.
Try adding tabindex="0" to the <table>. With this you make the <table> focusable with a click or pressing tab. However you may be interested on starting listening to key events as soon as the page is loaded. Then you should bind the event to document:
angular.element(document).bind(...)
If you bind to the table element, you won't get key events because the table doesn't have focus. See this question for info on which elements can have focus.
The events do bubble up however, so you can either add an invisible input or anchor element and get the keyboard events when they bubble up, or just listen on your document element to get any unhandled events. You can also check the ctrlKey flag on the key event instead of tracking the control key yourself:
var doc = angular.element(document);
doc.on('keyup', function(e) {
if (e.ctrlKey) {
if (e.keyCode === cKey) {
$scope.valueToBeCopied = e.target.value;
console.log('copy: valueToBeCopied: ' + $scope.valueToBeCopied);
}
if (e.keyCode === vKey) {
e.target.value = $scope.valueToBeCopied;
console.log('paste: valueToBeCopied: ' + $scope.valueToBeCopied);
}
}
});
I don't know how much that helps though with what you seem to be attempting. You'll have to track which element has the virtual 'focus' some other way.
Why is my click event fired twice in jquery?
HTML
<ul class=submenu>
<li><label for=toggle><input id=toggle type=checkbox checked>Show</label></li>
</ul>
Javascript
$("ul.submenu li:contains('Show')").on("click", function(e) {
console.log("toggle");
if ($(this).find("[type=checkbox]").is(":checked")) console.log("Show");
else console.log("Hide");
});
This is what I get in console:
toggle menu.js:39
Show menu.js:40
toggle menu.js:39
Hide menu.js:41
> $("ul.submenu li:contains('Show')")
[<li> ]
<label for="toggle">
<input id="toggle" type="checkbox" checked>
"Show"
</label>
</li>
If I remember correctly, I've seen this behavior on at least some browsers, where clicking the label both triggers a click on the label and on the input.
So if you ignore the events where e.target.tagName is "LABEL", you'll just get the one event. At least, that's what I get in my tests:
Example with both events | Source
Example filtering out the e.target.tagName = "LABEL" ones | Source
I recommend you use the change event on the input[type="checkbox"] which will only be triggered once. So as a solution to the above problem you might do the following:
$("#toggle").on("change", function(e) {
if ($(this).is(":checked"))
console.log("toggle: Show");
else
console.log("toggle: Hide");
});
https://jsfiddle.net/ssrboq3w/
The vanilla JS version using querySelector which isn't compatible with older versions of IE:
document.querySelector('#toggle').addEventListener('change',function(){
if(this.checked)
console.log('toggle: Show');
else
console.log('toggle: Hide');
});
https://jsfiddle.net/rp6vsyh6/
This behavior occurs when the input tag is structured within the label tag:
<label for="toggle"><input id="toggle" type="checkbox" checked>Show</label>
If the input checkbox is placed outside label, with the use of the id and for attributes, the multiple firing of the click event will not occur:
<label for="toggle">Show</label>
<input id="toggle" type="checkbox" checked>
I found that when I had the click (or change) event defined in a location in the code that was called multiple times, this issue occurred. Move definition to click event to document ready and you should be all set.
Not sure why this wasn't mentioned. But if:
You don't want to move the input outside of the label (possibly because you don't want to alter the HTML).
Checking by e.target.tagName or even e.target doesn't work for
you because you have other elements inside the label
(in my case it had spans holding an SVG with a path so e.target.tagName sometimes showed SVG and other times it showed PATH).
You want the click handler to stay on the li (possibly because you have
other items in the li besides the checkbox).
Then this should do the trick nicely.
$('label').on('click', function(e) {
e.stopPropagation();
});
$('#toggle').on('click', function(e) {
e.stopPropagation();
$(this).closest('li').trigger('click');
});
Then you can write your own li click handler without worrying about events being triggered twice. Personally, I prefer to use a data-selected attribute that changes from false to true and vice versa each time the li is clicked instead of relying on the input's value:
$('ul.submenu li').on('click', function() {
let _li = $(this),
ticked = _li.attr('data-selected');
ticked = (ticked === 'false') ? true : false;
_li.attr('data-selected', ticked);
_li.find('#toggle').prop('checked', ticked);
});
I need help with a script to add an "active" class to a div when a hidden checkbox is checked. This all happening within a somewhat complex form that can be saved and later edited. Here's the process:
I have a series of hidden checkboxes that are checked when a visible DIV is clicked. Thanks to a few people, especially Dimitar Christoff from previous posts here, I have a few simple scripts that handle everything:
A person clicks on a div:
<div class="thumb left prodata" data-id="7"> yadda yadda </div>
An active class is added to the div:
$$('.thumb').addEvent('click', function(){
this.toggleClass('tactive');
});
The corresponding checkbox is checked:
document.getElements("a.add_app").addEvents({
click: function(e) {
if (e.target.get("tag") != 'input') {
var checkbox = document.id("field_select_p" + this.get("data-id"));
checkbox.set("checked", !checkbox.get("checked"));
}
}
});
Now, I need a fourth ( and final ) function to complete the project (using mootools or just plain javascript, no jQuery). When the form is loaded after being saved, I need a way to add the active class back to the corresponding div. Basically reverse the process. I AM trying to figure it out myself, and would love to post an idea but anything I've tried is, well, bad. I thought I'd at least get this question posted while I work on it. Thanks in advance!
window.addEvents({
load: function(){
if (checkbox.checked){
document.getElements('.thumb').fireEvent('click');
}
}
});
Example: http://jsfiddle.net/vCH9n/
Okay, in case anyone is interested, here is the final solution. What this does is: Create a click event for a DIV class to toggle an active class onclick, and also correlates each DIV to a checkbox using a data-id="X" that = the checkbox ID. Finally, if the form is reloaded ( in this case the form can be saved and edited later ) the final piece of javascript then sees what checkboxes are checked on page load and triggers the active class for the DIV.
To see it all in action, check it out here: https://www.worklabs.ca/2/add-new/add-new?itemetype=website ( script is currently working on the third tab, CHOOSE STYLE ). You won't be able to save/edit it unless you're a member however, but it works:) You can unhide the checkboxes using firebug and toggle the checkboxes yourself to see.
window.addEvent('domready', function() {
// apply the psuedo event to some elements
$$('.thumb').addEvent('click', function() {
this.toggleClass('tactive');
});
$$('.cbox').addEvent('click', function() {
var checkboxes= $$('.cbox');
for(i=1; i<=checkboxes.length; i++){
if(checkboxes[i-1].checked){
if($('c_'+checkboxes[i-1].id))
$('c_'+checkboxes[i-1].id).set("class", "thumb tactive");
}
else{
if($('c_'+checkboxes[i-1].id))
$('c_'+checkboxes[i-1].id).set("class", "thumb");
}
}
});
// Add the active class to the corresponding div when a checkbox is checked onLoad... basic idea:
var checkboxes= $$('.cbox');
for(i=1; i<=checkboxes.length; i++){
if(checkboxes[i-1].checked){
$('c_field_tmp_'+i).set("class", "thumb tactive");
}
}
document.getElements("div.thumb").addEvents({
click: function(e) {
if (e.target.get("tag") != 'input') {
var checkbox = document.id("field_tmp_" + this.get("data-id"));
checkbox.set("checked", !checkbox.get("checked"));
}
}
});
});