How can i exclude some element from focusing out? - javascript

I have input. When i focus out on that input the focus out event gets triggered.
But under that input i am having
<div id="myDiv">
<ul>
<li>1</li>
</ul>
</div>
i want focus out event to be triggered when the inputs gets focus out - but when this under - when it is clicked - i don't want the focusing out of the input to ba happened.
I tried this here:
How to exclude Id from focusout
$('#id').focusout (function (e) {
if (e.relatedTarget && e.relatedTarget.id === 'dontFocusOut') {
return;
}
//do your thing
});
but it does not work for me - in event.relatedTarget i always get null.

You can do like this:
function my_fun(){
alert('Focus Out');
}
<input type="text" placeHolder="After focusout it will work" onfocusout="my_fun();" />

Related

Prevent html input focus being lost to the body tag

When I have focus on the input field and I click in any open area of the body, the body becomes the document.activeElement , Is there a way to prevent the body focus completely.
What I am looking for is :
To prevent focus the body and maintain focus on the input field.
To avoid the firing of the blur event on the input field.
I've tried adding tabindex=-1 but I believe its for Tab functionality and hence does not work in this case.
document.querySelector("#inpdontlosefocus")
.addEventListener("blur",function(){
const $log = document.querySelector("#log");
$log.innerText += "\r\nLost focus";
})
html,body {
width:100vw;
height: 100vh;
}
<body id="notokaytogetfocus">
<input id="inpdontlosefocus" type="" placeholder="dont lose focus to body">
<input id="inpokaytofocus" type="" placeholder="allow focus">
<div id="log"></div>
</body>
Here is a solution that will always keep the focus on input fields in your document:
you will be able to switch the focus between input fields.
if you clicked outside an element that is not input, it will get the lastest input blurred and will apply focus on it.
var blurred, focused;
const $log = document.querySelector("#log");
var els = document.querySelectorAll('input');
Array.prototype.forEach.call(els, function(el) {
el.addEventListener('focus', function() {
focused = this;
});
el.addEventListener('blur', function() {
$log.innerText += "\r\nLost focus;"
blurred = this;
});
});
document.addEventListener("click", function(e) {
e.preventDefault();
if (focused && focused.tagName == "INPUT") {
$log.innerText += "\r\nactiveElement= " + document.activeElement.id;
focused.focus();
} else if (blurred) blurred.focus();
})
html,
label {
width: 100%;
height: 100%;
}
<body id="notokaytogetfocus">
<input id="inpdontloosefocus" placeholder="dont loose focus to body">
<input id="inpokaytofocus" placeholder="allow focus">
<div id="log"></div>
</body>
I'd added more html elements for a more accurate demonstration, the logic here is if the event source in body is not focus-able then we set focus back to the input we want, other wise the its a focusable element thus will get the focus(e.g. button, link, input, ...); notice that click event is attached to body and clicking outside body won't have this behavior.
document.querySelector('.notokaytogetfocus').addEventListener("click",function (e){
if(e.target == document.activeElement){
console.log("focusable element");
}else{
console.log("not focusable element");
// we'll set foucs on desired input
document.querySelector("#inpdontlosefocus").focus()
}
})
.notokaytogetfocus{height: 100vh; width:100vw;}
<div class="notokaytogetfocus">
<input id="inpdontlosefocus" type="" placeholder="dont lose focus to body">
<input id="inpokaytofocus" type="" placeholder="allow focus">
<button>do!(focusable)</button>
<p>lorem ipsum</p>
<div>some text</div>
</div>

Usage of :not() to filter out elements in event handler

I'm pretty confused by the :not() selector. In plain CSS is seems to be rather straightforward:
section { /* Overriden as expected */
color: red;
}
input {
color: green; /* In effect as expected */
}
:not(input) {
color: blue; /* In effect as expected */
}
<section>
<p>Lorem ipsum</p>
<input value="Lorem ipsum">
</section>
However, when applied to filter the descendants of the selected elements that trigger an event I'm unable to grasp the logic:
jQuery(function($){
$(document).on("keydown", "input", function(event){
// This fires only for <input> as expected
console.log("Event handler #1 on", event.target);
});
$(document).on("keydown", ":not(input)", function(event){
// This fires for *all* elements :-?
console.log("Event handler #2 on", event.target);
// ... even though these checks return the results that intuition suggests
console.log('Is "input"? %s; Is ":not(input)"? %s',
$(event.target).is("input"),
$(event.target).is(":not(input)")
);
});
$(document).on("keydown", "section :not(input)", function(event){
// This *never* fires :-?
console.log("Event handler #3 on", event.target);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<p>Click and type here</p>
<input value="Click and type here">
</section>
What's the rationale behind the way :not() works here?
I'm really looking for an explanation as opposed to a fix.
The issue is that the keydown event bubbles up from the input. If you use :not(input), the handler will not fire when the event was just initialized at the input element, but it will fire when the event bubbles up to the section element. You can check this by checking this inside the function, which will refer to the element to which the event has bubbled when the handler fires. (The event.target will always be the input when you're typing in the input field)
jQuery(function($){
$(document).on("keydown", ":not(input)", function(event){
// This fires for *all* elements :-?
console.log("Event handler #2 on", this);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<p>Click and type here</p>
<input value="Click and type here">
</section>
If you continue adding :nots, you'll see it bubble up all the way up to the HTML tag:
jQuery(function($){
$(document).on("keydown", ":not(input):not(section):not(body)", function(event){
// This fires for *all* elements :-?
console.log("Event handler #2 on", this);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<p>Click and type here</p>
<input value="Click and type here">
</section>
I suppose you could use :not(input):not(section):not(body):not(html), but that's a bit silly and hard to manage.
Your third handler is properly excluding the input from firing the event, but only input (and similar) elements fire keydown events - it can't be fired from a <section>, for example. It might be clearer if there's a textarea child of the section as well as the input - you'll see that the textarea triggers the handler, but the input doesn't:
$(document).on("keydown", "section :not(input)", function(event) {
console.log("Event handler #3 on", event.target);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<section>
<p>Click and type here</p>
<input value="Click and type here">
<textarea></textarea>
</section>

JQuery UI Autocomplete, change event doesn't fire

I've some problems with JQuery Autocomplete, my code it's like:
var mySource = [{"label":"Value one","id":"1"},{"label":"Value two","id":"2"},{"label":"Value three","id":"3"}];
$("#txtAutocomplete").autocomplete({
source: mySource,
select: function(event, ui){
if(ui.item){
//console.log('select', ui.item.label);
$("#hiddenField").val(ui.item.id);
return ui.item.label;
}
else{
//console.log('select with null value');
$("#hiddenField").val('');
}
},
change: function(event, ui){
if(ui.item){
//console.log('change', ui.item.id);
$("#hiddenField").val(ui.item.id);
}
else{
//console.log('change with null value');
$("#hiddenField").val('');
}
}
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p>
<ol>
<li>Type 'Value' in the text box</li>
<li>Press 'arrow down' to select the first element</li>
<li>Press enter</li>
<li>Keep pressed backspace to delete completely the selected item</li>
<li>Press TAB</li>
<li>Value in 'readonly' field is still there</li>
</ol>
</p>
<input type="text" id="txtAutocomplete">
<input type="text" id="hiddenField" disabled="disabled">
<button>Button added just to have an element to focus on</button>
When I put the string 'value' in the editable field, autocomplete appears correctly, so I can select one value and put it in the textbox with id hiddenField.
Then, if I clear the value in the textbox, I can't update the related hiddenField with a blank value, because change event doesn't fire. Why?
Steps to test snippet:
Write 'value' in the editable field
Select one value
Clear the selected value
hiddenField will still contain old value.
Thanks
Note: It doesn't work when I clear the field after selection but still keeping the focus on it.
Updated: I reported the bug here on bugs.jqueryui.com
I have run to this problem and there is a hack to avoid the problem. You have to force a blur but with a setTimeout
if(ui.item){
//console.log('select', ui.item.label);
$("#hiddenField").val(ui.item.id);
setTimeout(function () {
$(event.target).blur();
});
return ui.item.label;
}
You don't have to keep the inputs in sync inside the autocomplete options. Attach a separate event handler to your text input like so:
$("#txtAutocomplete").autocomplete({
source: ['test1', 'test2', 'test3'],
select: function(event, ui){
console.log('select', ui.item.value);
$("#hiddenField").val(ui.item.value);
}
});
$("#txtAutocomplete").on("input propertychange", function () {
console.log("change", this.value);
$("#hiddenField").val(this.value);
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<input type="text" id="txtAutocomplete">
<input type="text" id="hiddenField" disabled="disabled">
When I run your code snippet, the change event does get fired each time I select an item, or when I clear the value, and the log gets printed. But the event gets fired only after I tab out after a selection, or after I click outside the auto-complete input element.
This is because, as per the documentation, the change event gets fired only when the element loses focus.
Steps that make it work:
Write 'test' in the editable field, and select an option
Tab out - this fires the change event
Delete the value
Tab out - this fires the change event

$('form:not(.some-class)').keydown is still applying keydown event to .some-class

JQuery's ':not' selector is not preventing the intended-to-be-excluded class (which decorates an element) from firing the .keydown event. Why?
From the following code, when I press a key in the .newOwnerEntryInput field, I expect to see the alert for '1' only. But I see both alerts '1' and '2'.
Javascript:
$('.newOwnerEntryInput').keydown(function (event) {
alert('1');
});
// Prevent Enter from submitting form.
$('form:not(.newOwnerEntryInput)').keydown(function (event) {
alert('2');
});
HTML:
<li style="position: relative">
#Html.DropDownList("cftMemberID", null, String.Empty, new { #class = "actionOwnerDropDown hidden" })
<div class="newOwnerEntryDiv">
<input class="newOwnerEntryInput" />
<div class="float-right closeNewOwner">
<img src="~/Images/cancel_x.png" alt="close" />
</div>
</div>
</li>
I have tried a variety of quotes styles, with and without surrounding the excluded class with quotes, as well as adding 'input' after the class, as in $('form:not(.newOwnerEntryInput input)').keydown
Thanks!
Thanks for those who helped. I do need the form to fire for ALL types of input fields, not just those of type input. So that was out.
Here is what solved my problem:
$('form').keydown(function (event) {
if (! event.which.hasClass('.newOwnerEntryInput')) {
alert('2');
}
});
In this case, for my input of class .newOwnerEntryInput, if a key is pressed, it will NOT fire the event and push '2' out to the alert screen.
Again, thanks, it took a couple responses, all of which had a piece of the solution, for me to answer this myself. :)
Try this:
HTML:
<div>
<input class="newOwnerEntryInput" type="text"/><br />
<!-- I know you have MVC dropdown list, but I replaced it with a html textbox (for simple testing) -->
<input class="newOwnerEntryInput1" type="text"/>
</div>
JavaScript:
$('input.newOwnerEntryInput').keydown(function (e) {
alert('1');
});
$('input:not(.newOwnerEntryInput)').keydown(function (e) {
alert('2');
});
I checked with the documentation that in their example, I saw they had the element input followed by the function with the selector.
The documentation is available is here: jQuery :not()
I hope this helps!
Cheers!
Try this :
$('form input:not(.newOwnerEntryInput)').on('keydown',function (event)
{
alert('2');
});
http://jsfiddle.net/rzseLj27/

How to make box appear when text is entered into input?

I have this HTML code:
<div class="center1">
<form>
<input type="text" class="input1" autofocus="focus" />
</form>
</div>
<br><br>
<div class="center1">
<div class="box"></div>
</div>
I have added it to this JSFiddle link: http://jsfiddle.net/PDnnK/4/
As you can see there is:
INPUT FIELD
&
BOX
I want the box to appear only when text is typed in the input. How is this done?
Start the box out with display: none. Then, you can capture the keypress event for the input:
document.getElementById('myInput').onkeypress = function () {
document.getElementById('myBox').style.display = 'block';
}
Something like this with jQuery:
$("#id-of-input").change(function() { $("#id-of-box"}.css('display', 'block'); } );
or change .change to .click
Binding to "change" is usually not super-handy, since it usually doesn't fire until you tab or click away from the element.
However, polling isn't the answer either.
original answer:
http://jsfiddle.net/xNEZH/2/
super-fantastic new answer:
http://jsfiddle.net/4MhKU/1/
$('.input1').bind('mouseup keyup change cut paste', function(){
setTimeout(function(){
var hasInput = $('.input1').val() != "";
$('.box')[hasInput ? 'show' : 'hide']();
}, 20);
});
The setTimeout is because cut and paste events fire BEFORE the text is cut or pasted.

Categories