I have two inputs
<input id="foo" name="foo"/>
<input id="bar" name="bar"/>
How to find cursor present in which input?
I am able to find position of cursor in it, but I need to know in which input cursor exists.
While other answers give you the current active element. I prefer to provide another answer which give you the exact 'which input' you asked.
<input id="foo" name="foo" onfocus="onfocus(this)" onblur="onblur(this)"/>
<input id="bar" name="bar" onfocus="onfocus(this)" onblur="onblur(this)"/>
<script>
var idOfInputFocused = ""; // what you need
function onfocus(input) {
idOfInputFocused = input.id;
}
function onblur(input) {
idOfInputFocused = "";
}
</script>
If you need to find the element that is currently active/on focus, use
document.activeElement
https://www.w3schools.com/jsref/prop_document_activeelement.asp
If the element has the cursor, it has the focus, you can find out using activeElement][1].
var activeElement = document.activeElement;
If you can't modify html, and need to know over which input cursor is positioned you can try such approach
document.addEventListener("mouseover", function(e) {
if(e.target.tagName === "INPUT") {
console.log(e.target.id);
document.getElementById("result").innerHTML = e.target.id;
}
});
Here you can find more information about events delegation - https://javascript.info/event-delegation, so you can wrap your inputs into some block and set event listener to that wrapper, listen any events on it and figure out what happened inside.
And be sure to remove event listener after necessary actions were performed)
Information about removing event listeners you can find here https://www.w3schools.com/jsref/met_element_removeeventlistener.asp.
link to test this solution https://www.w3schools.com/code/tryit.asp?filename=GB7P6V4ACH1O
Related
I am looking for a way to use eventlisteners and getting every color change by moving the mouse over the palette. It works only without eventlistener and I would like to know why. Where is my mistake...
It works, if I use the following code. Moving the mouse over the palette, fires every color change.
HTML:
<input type="color" id='picker_1' oninput="getData(this.value)">
Javascript:
function getData(value){console.log(value);
Using an eventlistener, I get only values by opening or closing the picker, but not with moving over the palette.
HTML:
<input type="color" id='picker_1'>
Javascript:
let el = document.getElementById('picker_1');
el.addEventListener('oninput', function() { // I tried also onchange
console.log(el.value);
});
The best solution would be to use the standard HTML5 color picker with jQuery...
Happy for some help. Thanks
There is no event as oninput when using addEventListener, you should remove the on prefix and use input instead.
let el = document.getElementById('picker_1');
el.addEventListener('input', function() { // I tried also onchange
console.log(el.value);
});
<input type="color" id='picker_1'>
I have an input field and a button. It is necessary that when the button is clicked the input field gets focus.
I need the behaviour to be slightly different depending on whether the input field was focused manually by the user or if it was focused due the button being clicked.
It seems this would be relatively simple, but I couldn't come up with a solution so far. Any ideas very welcome.
$("button").click(function() {
target_input = $("input");
target_input.focus();
});
$("input").focus(function() {
// if focus done manually by user
// do something
// if focus done via button
// do something else
});
Here is a solution that uses no extra variables, instead it checks the event.
$("button").click(function() {
target_input = $("input");
target_input.focus();
});
$("input").focus(function(e) {
// if focus done manually by user
// do something
// if focus done via button
// do something else
if(e.originalEvent.relatedTarget){
// only from button events
}
// here is from all events
});
this e.originalEvent.relatedTarget will return null if we didn't use the button to originate the focus.
remember to add e to the function.
You should be able to use Event.isTrusted for this:
The isTrusted read-only property of the Event interface is a boolean
that is true when the event was generated by a user action, and false
when the event was created or modified by a script or dispatched via
dispatchEvent.
$("input").focus(function(e) {
if(e.isTrusted) {...} else {...}
});
As noted in the comments, neither IE nor Safari like this.
This works without global variables and it is cross-browser working solution:
$('button').click(function () {
$(this).prev('input').focus()
})
$('input').click(function (e) { // yes, listen to click instead
// original event exists only if input was clicked directly
if (e.originalEvent) {
console.log('manually triggered')
}
})
<div style="background-color: yellow;">
<input type="text">
<button>Focus input</button>
<br>
<input type="text">
<button>Focus input</button>
</div>
<script src="https://unpkg.com/jquery"></script>
There is a div and it contains input type text element inside it, this div gets visible on some button click and input gets focused every time, input inside div contain blur event and in that event it has to perform some calculations.
Now problem I am facing is when I set display none of that div its blur event is called although it is very logical.
<div id="main-container">
<div id="main">
<input type="text" id="name" />
</div>
<input type="button" id="btn" value="click me"/>
I have to avoid those calculations that is performed in blur event when its style property is display none so for this I place a check in blur event i.e.
if(style!='none')
This solves my problem but the purpose of writing this question here is to find a nice and efficient way to handle this problem?
It sounds like you've already solved the problem but are looking for an alternative. Unfortunately, there really isn't much else you can do aside from checking for visibility before doing your calculations.
You might want to just add the check in your blur event, if you haven't already:
var main = document.getElementById( 'main' );
document.getElementById( 'name' ).onblur = function() {
if( main.style.display != 'none' ) {
// do calculations
}
};
If, for whatever reason, you don't want to check the style.display, you could do a check similar to jQuery:
if( main.offsetWidth > 0 && main.offsetHeight > 0 ) {
// do calculations
}
var x = document.getElementById('btn');
if(x.style.display != 'none')
// do calculations
I'm working on a project with an autocomplete searchbox. Now I have the issue that I want to pass the value from the found autocompleteresults to the input box, but on the same time, I want the autocompletebox to hide when the inputfield is not more focused.
Now I have a conflict going on with both of them since the click on the autocompletebox is seen as focusout and hide the box even before it can pass the value. Any pointers or workarounds for this kind of issue? Here a jsfiddle to make it more clear to you.
http://jsfiddle.net/KeGvM/
Or here
CSS:
#a_c {display:none;}
JS:
$('#search_field').focusout(function() {
$('#a_c').hide(); // IF I DELETE THIS IT WORKS
});
$('#search_field').focusin(function() {
$('#a_c').show();
});
$('#a_c a').click(function() {
$('#search_field').val('');
var value = $(this).text();
var input = $('#search_field');
input.val(input.val() + value);
$('#a_c').hide();
return false;
});
HTML:
<input autocomplete="off" onkeyup="searchFor(this.value);" name="search" id="search_field" class="bold" type="text" placeholder="Search...">
<div id="a_c">hello world</div>
The way I solved this was using the mousedown event instead of click. The mousedown event is always triggered before the focusout event while click is not.
You can try it out in the little demo below. Focus on the field and then click on the button.
const field = document.getElementById('field');
const btn = document.getElementById('btn');
btn.addEventListener('click', () => console.log('Click'));
btn.addEventListener('mousedown', () => console.log('Mouse down'));
field.addEventListener('focusout', () => console.log('Focus out'));
<input id="field">
<button id="btn">Try it</button>
As you can see the output is in the following order:
Mouse down
Focus out
Click
This is the most stable solution without using any workaround hacks like timeouts. It also does not depend on jQuery. The only thing worth noting that mousedown does not wait for the user to release their mouse button, but in terms of user experience that is not really a concern here.
How about using
:hover
I solved same problem using it.
$('className').on('focusout', function(e) {
if($('.suggestLi' + ':hover').length) {
return;
}
$('.suggestList').empty();
});
My solution in the similar situation was using timeout to temporarily hold off the action taken in blur event handler. Like this:
$('#search_field').focusout(function() {
window.setTimeout(function() { $('#a_c').hide() }, 100);
});
I have a pretty simple scenario. I have the following HTML:
<h1>Hello</h1>
<input type="button" value="Change" id="change" />
With the corresponding JS:
var h1 = $("h1").get(0);
h1.addEventListener("DOMSubtreeModified", function(ev) {
console.log("Changed");
ev.bubbles = false;
ev.cancelBubble = true;
ev.defaultPrevented = true;
ev.preventDefault();
ev.stopPropagation();
ev.returnValue = false;
return false;
}, false);
$("#change").click(function() {
$("h1").text("World");
});
So, this basically just changes the text of the H1 node and the event is then fired. However, the event is firing twice (as I assume as a result of bubbling). As you can see, I've tried throwing everything at it to try to get it to not fire twice, but that does not stop it. If you want to play with the code, you can check it out at: http://jsfiddle.net/sECtq/. Any help would be appreciated.
This behaviour is not caused by bubbling.
$.text() executes 2 steps to set the new text:
remove the existing contents
insert a new textNode
Both steps trigger DOMSubtreeModified, so you get 2 alerts.
You may use e.g. the following:
$("h1")[0].firstChild.data="World";
This will only change the contents of the textNode without removing a node.
or you can also check whether propagation has been stopped or not. Take a look on the http://api.jquery.com/event.isPropagationStopped l