How to keep track of focused elements in a form - javascript

I'm new to vuejs and I'm wondering what would be the best way to keep track of the latest focused input/textarea in a form in order to programatically modify their values from the parent component.
Example
Form
Input1
Input2 -> focused
Textarea
Button (onclick -> appends "hello" to the focused input)

Answer:
You can create a data property that tracks the currently focused/last focused input element. In the below example this is called current_focus.
To do this you could use the focus event - but because focus doesn't bubble you would have to apply it to each individual input element manually.
It is easier to provide a focusin event handler to the parent. This event, unlike focus, bubbles up the DOM from any child to its parent. This allows you to utilize an event delegation pattern.
Event Delegation means that you apply one handler to a parent for an event, then do something depending on the source of the event. This means when we receive a focusin event, we can simply check if the focused element is an input element, then update our data property ( current_focus )
Code Sandbox Example:
https://codesandbox.io/s/focus-handler-vzip0
Code Example:
FocusDemo.js
<template>
<div v-on:focusin="updateFocus">
<input name="one">
<br>
<input name="two">
<br>
<input name="three">
<br>
<button #click="handleClick">Add Text To Focused</button>
</div>
</template>
<script>
export default {
name: "FocusDemo",
data: function() {
return {
current_focus: undefined
};
},
methods: {
updateFocus: function(e) {
let element = e.target;
if (element.matches("input")) {
this.current_focus = element;
}
},
handleClick: function(e) {
if (this.current_focus) {
this.current_focus.value = "Button was clicked!";
}
}
}
};
</script>

Related

Click event on label not firing (class doesn't change)

I have a checkbox inside a label. I added the event listener for the click event to the label, so as to trigger the class.
It does work when I click the checkbox.
However, if I click the label, nothing changes. Why is that, considering that the event is binded to the label and not the checkbox?
const formCheck = document.querySelector('.drinos-checker')
formCheck.addEventListener('click', function () {
formCheck.classList.toggle('checkerActive')
})
.checkerActive {
background-color: red;
}
<label class="drinos-checker"><input class="drinos-checkbox" type="checkbox" name="checkbox" value="value">Renovation</label>
Consider this simple example:
const formCheck = document.querySelector('.check')
formCheck.addEventListener('click', function () {
console.log("clicked!")
})
<input class="check" type="checkbox">
When you check the checkbox, you can see that the event is captured and then logged.
What happens if we then add a label?
Let's do that. If we then leave the code unchanged, appears that a click on a label does also trigger our click event, though it was binded to the checkbox.
const formCheck = document.querySelector('.check')
formCheck.addEventListener('click', function () {
console.log("clicked!")
})
<label><input class="check" type="checkbox">A label</label>
That's how it works. But we're not finished yet...
What happens if I bind the event on the label, not on the checkbox?
const formCheck = document.querySelector('label');
formCheck.addEventListener('click', function () {
console.log("clicked!")
})
<label><input class="check" type="checkbox">A label</label>
You have seen that correct: the click event triggers two times. But how is it even possible? Let's break down what happens here:
the label works this way that it triggers a click event in the checkbox
once you click the label, the event that you binded is triggered
but since the label itself "clicks" the checkbox, the event is triggered again, because the checkbox is in the label. This way, the event is called twice.
So, what does it mean?
You may have understood that already: the class doesn't change because it toggles two times on a single click. I.e. it toggles and then immediately toggles again, which results in you not noticing any changes.
How can one fix that?
There's a quick fix: you could replace your click event with change event. This way:
the label triggers checkbox
the change event on checkbox is called
the label itself doesn't have a change event, thus everything works as intended
"Working-as-intended" example:
const formCheck = document.querySelector('.drinos-checker')
formCheck.addEventListener('change', function () {
formCheck.classList.toggle('checkerActive')
})
.checkerActive {
background-color: red;
}
<label class="drinos-checker"><input class="drinos-checkbox" type="checkbox" name="checkbox" value="value">Renovation</label>
Instead of adding click event to the label, add it to the input element -
const formCheck = document.querySelector('.drinos-checker');
const inputCheck = document.querySelector('input');
inputCheck.addEventListener('click', function() {
formCheck.classList.toggle('checkerActive')
})
.checkerActive {
background-color: red;
}
<label class="drinos-checker"><input class="drinos-checkbox" type="checkbox" name="checkbox" value="value">Renovation</label>

Why does preventDefault on parent element disable programmatically checking child checkbox on click?

A div element's click event has e.preventDefault() at the beginning. That makes manually clicking the checkbox input or it's associated label inside no longer works.
With the help of some more JavaScript code, manually clicking the label generates expected results because the checkbox is now programmatically checked/unchecked.
However, manually clicking the checkbox input still does not work despite the fact that similar JavaScript code for programmatically checking/unchecking has been implemented. Why?
document.querySelector('div').onclick = function (e)
{
e.preventDefault();
if (e.target.tagName.toUpperCase() == 'LABEL')
{
e.target.previousElementSibling.checked = !e.target.previousElementSibling.checked;
}
else if (e.target.tagName.toUpperCase() == 'INPUT')
{
e.target.checked = !e.target.checked;
}
}
<div>
<input id="check" type="checkbox">
<label for="check">Label Text</label>
</div>
Prevent default propagates often propagates down to the child. There is a way to stop that from happening by using using event.stopPropagation. Read here to learn more about other useful methods that might help your cause.
https://chunkybyte.medium.com/the-one-with-event-propagation-and-e-preventdefault-part-1-6d84f3c4220
Clicking the label sets the checked property as expected because there is no default action related to the label to be canceled. Clicking the input sets the property as expected, but due to the default action (toggling the checked property) being prevented it reverts to its previous state.
see: Why does preventDefault on checkbox click event returns true for the checked attribute? for more in depth discussion.
document.querySelector('div').onclick = function (e)
{
e.preventDefault();
if (e.target.tagName.toUpperCase() == 'LABEL')
{
e.target.previousElementSibling.checked = !e.target.previousElementSibling.checked;
}
else if (e.target.tagName.toUpperCase() == 'INPUT')
{
console.clear();
console.log(e.target.checked);
e.target.checked = !e.target.checked;
console.log(e.target.checked);
}
}
<div>
<input id="check" type="checkbox">
<label for="check">Label Text</label>
</div>
Edit
In response to your comment I think the cleanest solution would be to explicitly apply listeners to those elements that you want to control outside of the provided API methods calling stopPropagation() on them to avoid triggering the parent listeners.
You can then handle whatever logic you need without having to work around artifacts of the outside methods. If you need the parent to listener to run as well you can programmatically activate it after your control logic is finished.
// original API listener
document.querySelector('.container').addEventListener('click', function (e) {
e.preventDefault();
// add container specific code
console.log('clicked div');
});
// your isolated listener
document.querySelector('.checkbox-container').addEventListener('click', function (e) {
e.stopPropagation(); // stop the event from propagating to the parent listener
// add checkbox specific code
console.clear();
console.log('clicked checkbox container');
// even programmatically 'clicking' parent if you need to
e.currentTarget.parentElement.click();
});
.container {
width: 150px;
height: 60px;
background-color: lightgray;
}
.checkbox-container {
display: inline-block;
background-color: aquamarine;
}
<div class="container">
<div class="checkbox-container">
<input id="check" type="checkbox">
<label for="check" >Label Text</label>
</div>
</div>

Javascript - trigger custom parent html event from child element

I am trying to trigger a custom event in a parent element from the child elements event. The parent element is HelpMenuHeader and it's custom event is defined in HTML as "onsubmenu_click".
Here's a snippet of the HTML that just shows one menu tree.
<span class="formMenu" id="HelpMenuHeader" onsubmenu_click="OnMenuClick()">Help
<div class="formMenu" id="HelpAbout" onmouseup="MenuChildClick()">About us...</div>
</span>
In the child element, HelpAbout, the MenuChildClick event needs to trigger the parent's onsubmenu_click event so that that will execute (that event handler uses the parent's information).
Here's a snippet of the javascript I have for MenuChildClick:
function MenuChildClick()
{
var srcElement = this.event.srcElement;
if (srcElement.id != "spacer" && srcElement.tagName != "HR")
{
// NONE OF THE LINES BELOW WORK
//parent.$(srcElement).trigger('onsubmenu_click');
//$(srcElement).trigger('onsubmenu_click');
//var event = document.createEvent('Event');
//event.initEvent('submenu_click', true, true, null);
//srcElement.dispatchEvent(event);
//oEvent = createEventObject();
//oEvent.result = srcElement.id;
//onsubmenu_click.fire(oEvent);
}
}
I'm having a problem getting a reference to the correct parent element in the MenuChildClick event because when I check the parent reference doesn't have the parent ID.
And then once I have the correct parent reference I need to execute the parent's onsubmenu_click custom event. (The parent event is already being listened to since it's defined in the HTML, right?)
I have to support IE compatibility view so I need it to work for previous IE versions as well.
Anyone tell me how I can do these things (1 & 2 above) leaving the HTML as it is?
Thanks in advance.
You can use jQuery methods .on() and .trigger() instead of event handler attribute
$(function() {
function parentHandler(event, args) {
console.log(event.type, args)
}
$("#HelpMenuHeader").on("submenu_click", parentHandler);
$("#HelpAbout").on("mouseup", function() {
$(this).parent().trigger("submenu_click"
, ["triggered from #" + this.id])
})
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<span class="formMenu" id="HelpMenuHeader">Help
<div class="formMenu" id="HelpAbout">About us...</div>
</span>
First you have to pass the element that is triggering the event in your HTML by changing your HTML to this:
<span class="formMenu" id="HelpMenuHeader" onsubmenu_click="OnMenuClick()">Help
<div class="formMenu" id="HelpAbout" onmouseup="MenuChildClick(this); return false;">About us...</div>
</span>
Notice that I pass the element that is triggering the function call by passing 'this' through the onmouseup function call.
Then you can use the passed element to define which elements you want to monitor as follows:
function MenuChildClick(element)
{
var srcElement = element;
var parent = element.parentNode
if (srcElement.id != "spacer" && srcElement.tagName != "HR")
{
//parent.trigger('onsubmenu_click');
}
}

Prevent function execution twice within two triggered events

I have the following code:
myInput.change(function (e) { // this triggers first
triggerProcess();
});
myButton.click(function (e) { // this triggers second
triggerProcess();
});
The problem with the above is when I click myButton both events are triggered and triggerProcess() is fired twice which is not desired.
I only need triggerProcess() to fire once. How can I do that?
Small demo
You can have a static flag that disables any more triggers once the first trigger has occurred. Might look something like this:
var hasTriggered = false;
myInput.change(function (e) { // this triggers first
triggerProcess();
});
myButton.click(function (e) { // this triggers second
triggerProcess();
});
function triggerProcess () {
// If this process has already been triggered,
// don't execute the function
if (hasTriggered) return;
// Set the flag to signal that we've already triggered
hasTriggered = true;
// ...
}
For resetting the hasTriggered flag, that's entirely up to you and how this program works. Maybe after a certain event occurring in the program you'd want to reenable the ability to trigger this event again — all you'd need to do it set the hasTriggered flag back to true.
You can use the mousedown event, which will fire before the input is blurred, and then check if the input has focus by checking if it's the activeElement, and if it does have focus, don't fire the mousedown event, as the change event will fire instead.
Additionally, if you want a mousedown event to occur when the value hasn't changed, and the change event doesn't fire, you'll need a check for that as well
var myInput = $('#test1'),
myButton = $('#test2'),
i = 0;
myInput.change(function(e) { // this triggers first
$(this).data('prev', this.value);
triggerProcess();
});
myButton.mousedown(function(e) { // this triggers second
var inp = myInput.get(0);
if (document.activeElement !== inp || inp.value === myInput.data('prev'))
triggerProcess();
});
function triggerProcess() {
console.log('triggered : ' + (++i))
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="test1">
<br />
<br />
<button id="test2">
Click
</button>
In a fairly typical scenario where you have an input with a button next to ie, eg quick search.
You want to fire when the input changes (ie onblur) but also if the user clicks the button.
In the case where the user changes the input then clicks the button without changing input focus (ie no blur), the change event fires because the text has changed and the click event fires because the button has been clicked.
One option is to debounce the desired event handler.
You can use a plugin or a simple setTimeout/clearTimeout, eg:
$('#inp').change(debounceProcess)
$('#btn').click(debounceProcess);
function debounceProcess() {
if (debounceProcess.timeout != null)
clearTimeout(debounceProcess.timeout);
debounceProcess.timeout = setTimeout(triggerProcess, 100)
}
function triggerProcess() {
console.log('process')
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input id="inp">
<button id="btn">Click</button>
Use a real <button>BUTTON</button>. If you click on input text, alert is triggered, then once you leave the input text to click anywhere else, that unfocuses the input text which triggers the change event, so now 2 events have been triggered from the text input.
This is an assumption since the code provided is far from sufficient to give a complete and accurate answer. The HTML is needed as well as more jQuery/JavaScript. What is myInput and myButton actually referring to, etc.?
So I bet if you change...
var myButton = $('{whatever this is}'); and <input type='button'>
...TO:
var myButton = $("button"); and <button></button>
...you should no longer have an event trigger twice for an element.
This is assuming that triggerProcess() is a function that does something that doesn't manipulate the event chain or anything else involving events. This is an entirely different ballgame if instead of click() and change() methods you are using .trigger() or triggerHandler(), but it isn't. I'm not certain why such complex answers are derived from a question with very little info...?
BTW, if myInput is a search box and myButton is the button for myInput, as freedomn-m has mentioned, simply remove:
myButton.click(...
Leave myButton as a dummy. The change event is sufficient in that circumstance.
SNIPPET
var xInput = $('input');
var xButton = $('button'); //«———Add
xInput.on('change', alarm);
xInput.on('click', alarm);
xButton.on('click', alarm);
function alarm() {
return alert('Activated')
}
/* For demo it's not required */
[type='text'] {
width: 5ex;
}
b {
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id='f1' name='f1'>
<input type='text'>
<input type='button' value='BUTTON TYPE'>
<label><b>⇦</b>Remove this button</label>
<button>BUTTON TAG</button>
<label><b>⇦</b>Replace it with this button</label>
</form>

JQuery focus to previous clicked input bug

I have two input fields. The main idea is that whenever you focus to one of the fields, the button click should print a random number inside it.
My problem is that when you just focus on (click on) the first field, then focus on second (or vice versa), the button click prints to both instead of just to the (last) focused field.
You can try to recreate the problem here: http://jsfiddle.net/sQd8t/3/
JS:
$('.family').focus(function(){
var iD = $(this).attr('id');
$("#sets").one('click',function() {
var ra = Math.floor((Math.random()*10)+1);
$('#'+iD).val(ra);
});
});
HTML:
<center class='mid'>
<input type="text" class="family" id="father" />
<br/><br>
<input type="text" class="family" id="mother" />
<br/>
<br/>
<input type='submit' value='Set text' id="sets"/>
</center>
In the "focus" handler, unbind any existing "click" handler:
$('#sets').unbind('click').one('click', function() { ... });
The way you had it, an additional one-shot "click" handler is bound each time a field gets focus, because jQuery lets you bind as many handlers as you like to an event. In other words, calling .one() does not unbind other handlers. When the click actually happens, all handlers are run.
edit — sorry - "unbind" is the old API; now .off() is preferred.
Put the variable iD outside, and separate the functions:
http://jsfiddle.net/sQd8t/8/
This prevents from adding too many events on each input click/focus.
No need to unbind.
var iD;
$('.family').focus(function() {
iD = $(this).attr('id');
});
$("#sets").on('click', function() {
var ra = Math.floor((Math.random() * 10) + 1);
if (iD!="")$('#' + iD).val(ra);
iD = "";
});
See http://jsfiddle.net/sQd8t/11/
$('.family').focus(function(){
$("#sets").attr('data-target',$(this).attr('id'))
});
$("#sets").click(function() {
var target=$(this).attr('data-target');
if(target){
var ra = Math.floor((Math.random()*10)+1);
$('#'+target).val(ra);
}
});
You can create a data-target attribute which contains the field which must be modified.

Categories