How to prevent an element from losing focus? - javascript

How to keep the Focus on one textbox ? even if you click anywhere in a browser.
$("#txtSearch").focus();

You need to subscribe to the blur event of the textbox and reinstate focus with a small timeout:
$('#txtSearch').blur(function (event) {
setTimeout(function () { $("#txtSearch").focus(); }, 20);
});
This way you don't rely on subscribing to the events of any other element on the page. If you subscribe to body click or html click, it won't run if any other element prevents propagation of its click event, also it won't work when tabbing out of the textbox.
Example:
<!-- I will not propagate my click to top level DOM elements -->
<button id="button">Click me</button>
<script>
$('#button').click(function (event) {
event.stopPropagation();
});
</script>

Konstantin Dinev answer works ok in most cases, but if you dont want to lose the focus only when clicking on certain parts of the html just do this:
$(".nofocus").on( "mousedown", function (e) {
return false;
});
In my case i'm doing a small html text editor and i dont want to lose the control when pressing an action button, but yes in any other case.
I just need to add the nofocus class to the button and it will not take the control

$("html").click(function(){
$("#txtSearch").focus();
});
Live Demo: http://jsfiddle.net/QhaLY/

It's also possible without jQuery and without re-focusing, if you just need a click on specific elements to not grab the focus
just listen for the mousedown event and cancel it
element.addEventListener("mousedown", event => {event.preventDefault(); event.stopPropagation()});

$('body').click(function(){$("#txtSearch").focus();});

There are other ways of loosing focus than clicking area away from the input i.e. tabbing. If you want to prevent loosing focus use blur event i.e.
document.getElementById('txtSearch').addEventListener('blur', e => {
e.target.focus();
});

I use onMouseDown={e => e.preventDefault()} and that works just fine.

Related

How do I detect when the user changes between inputs pressing 'tab' using jQuery?

I have a view with a form. The form has many inputs, and I would need detect when the user moves between them (clicking or pressing 'tab').
For now I have this:
$('input').on('click',function(){
// Do something
});
But I would need detect if the user focus on these input even if he doesn't use the mouse.
Thank you
How about focus?
$('input').on('focus',function(){
// Do something
});
The focus event is sent to an element when it gains focus. This event is implicitly applicable to a limited set of elements, such as form elements (<input>, <select>, etc.) and links (<a href>).
https://api.jquery.com/focus/
For all text inputs inside the form
$(document).ready(function () {
$('form').on('focus blur', 'input', function () {
// Handle event
});
});
You need to use focus event instead of click:
$('input').on('focus',function(){
// Do something
});

Blur event not works for div

Here is my code below I'm trying to hide addstuff id div when clicked out of it. I tried body click event but it was useless. So I need a trigger event like blur. But It doesn't work for both blur and focusout events.
$(document).ready(function() {
$('#addstuff').blur(function () { $('#addstuff').fadeOut() })
})
There is no blur event for div. You can create that effect using the click event of body.Note that you should exclude that div from the click event
$(document).ready(function () {
$("body").not("#addstuff").click(function (e) {
$("#addstuff").fadeOut();
});
});
Fiddle
Edit
As #TrueBlueAussie suggested, it would be better to use document instead of 'body' for the click event handler:
$(document).not("#addstuff").click(function (e) {
$("#addstuff").fadeOut();
});
There's no way you can use .blur with a div, it has to be with some input field.
You can always use mouse events like
$(document).ready(function(){
$("#addstuff").mouseleave(function(){
$(this).remove();
});
});
http://jsfiddle.net/asrF2/
You can also use the HTML5 global attribute contenteditable (don't forget to set it true or false)
<div id="#addstuf" contenteditable="true">bla bla</div>
I don't recommend this that much, because of mobile browsers' compatibility.
divs have no focus and blur events, but you can add a contenteditable attribute so that you can type in that div, so the blur actually gets fired:
<div id="addstuff" contenteditable></div>
Then your jquery code works.
You can add additional functions to prevent people from actually typing in that div.
Alternatively you can use the .mouseleave() or .mouseout() event.
div element cannot be focused on so the blur function of jquery cannot be applied to it. See existing answers from our Stack Exchange buddies below for elements that focus can be applied on.
Which HTML elements can receive focus?

How do you avoid losing focus on a contenteditable element when a user clicks outside that element?

I want to prevent a contentEditable area from losing focus if a click is made outside that area. Some sample HTML looks like this:
<div id="content">
<p>Hello</p>
</div>
<div id="clickThis">
<p>If you click on this or anywhere for that matter after focusing on Hello, you lose your focus on Hello</p>
</div>
Sample Javascript looks as follows:
$(document).ready(function()
{
$('#content')[0].contentEditable=true;
$('#clickThis').bind('click',function(e)
{
console.log(window.getSelection().getRangeAt(0).startContainer);
e.preventDefault();
});
});
When you click on the #clickThis div or anywhere outside the #content div, you lose focus on the #content div even if you call the click event's preventDefault function.
In addition, the range changes the moment the click event is fired, so I can't just return to the previous range after the click has occurred. Is there a way to maintain the cursor position and focus after a click occurs?
jsFiddle: http://jsfiddle.net/VivekVish/FKDhe/4/
Putting Juan's question into an answer, instead of using the click event, you have to use the mousedown event as follows:
$(document).ready(function()
{
$('#content')[0].contentEditable=true;
$('#clickThis').bind('mousedown',function(e)
{
console.log(window.getSelection().getRangeAt(0).startContainer);
e.preventDefault();
});
});
You can see it working here:
http://jsfiddle.net/FKDhe/7/
The answer is to add event.preventDefault() to the mouseDown event.
const button = document.getElementById('boldFormat')
button.addEventListener('mousedown', (event) => {
event.preventDefault() // prevent loss of focus
document.execCommand('bold', false)
})
The problem occurred because the you are listening to the click event which causes the contentEditable element to lose focus; regardless of whether you run preventDefault or not.
try adding $('#content').focus(); after e.preventDefault();
it's not a perfect solution, since it jumps to the beginning, but give it a try.
anyway, are you sure it's a good idea to force the user back to this area? :)

JS jQuery Hiding element on unfocus stops other events from being fired

I have a search suggestion box that I hide when the search text box loses focus. This works great, except that when I click one of the suggestions the click event for that suggestion does not fire.
searchText.focusout(function () { $("#search-suggestions").hide(); });
I also tried:
searchText.focusout(function () { $("#search-suggestions").css("visibility", "hidden"); });
I tried commenting out the hide on unfocus code and the click events then worked fine.
(Basically, the blur event happens before the click on the suggestion can be registered, such that the element I attempted to click is not on the screen when the clicm does register)
here's the click event code:
//Called after the ajax load
$("#search-suggestions").find("a").click(function () { alert("hi"); })
I also tried rendering this on the server but it failed as well:
Search Suggestion
If any one has any suggestions I would appreciate it. Thanks!
You could try to define something like this:
//this goes where you first binding focusout handler
searchText.focusout(onFocusOut);
//this is a usual function
function onFocusOut() {
$("#search-suggestions").hide();
}
//this could be defined after you draw the search-suggestions control
$("#search-suggestions").hover(function() {
//this is hover in handler; unbind focusout from searchText
//something like that:
$("#searchText").unbind('focusout', onFocusOut)
}, function() {
//this is hover out handler; bind focusout to searchText
//something like that:
$("#searchText").bind('focusout', onFocusOut)
});
you could also use live (http://api.jquery.com/live/) to define hover handler for #search-suggestions, depending on what exactly you need.
This will make your search suggestions stay visible when clicking them. In click handler you can then hide them.
Try just making it invisible.
Change $('#my_search_box').hide(); to $('#my_search_box').css('visibility','hidden');
If you have surrounding DOM elements that need to act as if the search box is gone, you can just assign it an absolute position as well.
Try using .css('visibility', 'hidden') instead of .hide which uses display:none.

jquery offclick?

I have a 'li' that pops down when I click on a 'link' via jquery's 'click'.
Does anyone know of a clean way to do something along the lines of 'offclick'? As in, when I click off of the element, it would hide the pop down?
Thanks!
Matt
You would want to assign a click listener to the window and also assign the click listener to your link. Inside the link click listener, you'll want to stop the event propagation so it doesn't travel up the DOM tree and fire your window's click listener.
Something like this should do the trick:
$(window).click(function(){
$('li#my_li').slideUp();
});
$('a#my_link').click(function(event){
try
{
event.stopPropagation();
}
catch(err)
{
// IE does it this way
window.event.cancelBubble=true;
}
$('li#my_li').slideDown();
});
I guess you could look at blur, which is called when the element looses focus:
ref: http://api.jquery.com/blur/
You can use blur or focusout depending on your needs

Categories