Angularjs focus unexpectedly requires an async setTimeout to work - javascript

Ok StackOverflow, riddle me this.
I have a button that I click on which toggles the visibility of an input. In the scope function which changes the visibility I use javascript to set focus on that input tag. What I want to know is why does it not work unless I wrap it in a setTimeout?
$scope.toggle = function() {
if ($scope.hideInput) {
setTimout(function(){
input.focus();
}, 0); // That's right, zero!
}
$scope.hideInput = !scope.hideInput;
};
Here's a working jsfiddle with a button that correctly sets the focus and a button that doesn't:
http://jsfiddle.net/PsS99/1/

Can tell you the reason why.
First you can't focus element, with css display:none.
So in the one (broken) method, you focus the element before it is actually displayed.
Because the angular will go line to line and $scope.hideInput = !scope.hideInput; will trigger the watcher for a digest-loop. In that loop your input will be set to display: block.
The timeout will move the focus command into it's own thread, and the $scope.hideInput = !scope.hideInput; will trigger the digest, too.
But the digest is curiously fast enought to display the element before the input.focus(); will be executed.
This is my explanation but understanding this, did help me in some curious problems of angular's timing.
Maybe use this ? http://ngmodules.org/modules/ng-focus-on
A directive to set the focus by variable.

Related

jQuery/JS setTimeout() still runs after clearTimeout() called

I have an input type="number" and am using the up/down arrows within the field to change the value of the input. I want to trigger a function after the final click/change of the input.
By final I mean after the input hasn't been changed for 1000ms (my assumption that the user has now stopped clicking).
I've set up a 1000ms setTimeout() that runs the function, but even though I'm calling clearTimeout() .on('change') of the input, the function runs 1000ms after the first change, rather than the last.
I've set up a simple JSFiddle to illustrate what I mean. The div with "Hello World!" in it should not appear until after the final click.
If you rapidly click the up arrow on the input (at least once every 999ms) then the div should never appear.
I have looked through a lot of other similar questions on here but they're almost all about the scope of the timer variable, which I don't think applies here.
What am I doing wrong?
onchange, is triggered when input loses its focus, try on input.. btw. jquery is not required here.
var timeOut;
document.getElementById("foo").addEventListener("input", function() {
clearTimeout(timeOut);
timeOut = setTimeout(function() {
document.getElementById("bar").style.display = "block";
}, 1000);
});

.focus() not working on textarea in hover event

So I have this code here.
timeline.afterMilestonePrototypeCreated = function() {
$(MILESTONE_PROTOTYPE_SELECTOR).hover(function(e){
$(this).find('textarea').focus();
});
}
Which should focus the textarea element after it was created. Everything works fine, I've even checked if the event is being called, after creation and hovering. Every other code works, but I'm not able to focus that textarea element. After some googling I've tried to add a setTimeout, which didn't work neither.
Thanks!
SOLVED:
The parent element of the textarea is a dot, and after hovering the dot it becomes a bigger circle and than it's inner elements are becoming visible. The problem was, that when adding the timeout the duration I've set was to short so the css transition for making the textarea visible was still going that's way it wasn't focusing.
Instead of this:
$(this).find('textarea').focus();
Try this:
$(e.target).find('textarea').focus();
This may work, as long as $(this).find('textarea') works as expected:
timeline.afterMilestonePrototypeCreated = function() {
$(MILESTONE_PROTOTYPE_SELECTOR).hover(function(e){
e.preventDefault();
$(this).find('textarea').focus();
});
}
A hover event triggers a focus event, so preventing it will allow the manual focus to occur.

JQuery if statement for .is(':visible') not working

I have a div that when the page is loaded is set to display:none;. I can open it up using this simple code:
$(".field-group-format-toggler").click(function()
{
$(".field-group-format-wrapper").css({'display':'block'});
});
Once it's opened, I'd like the user to be able to close it so I tried using the .is(':visible') function and then wrapping my original code in an if statment but this time using display:none;
if($('.field-group-format-wrapper').is(':visible')){
$(".field-group-format-toggler").click(function()
{
$(".field-group-format-wrapper").css({'display':'none'});
});
}
This does not seem to work though and I am not getting any syntax errors that I know of.
I also tried this:
if ($('.field-group-format-wrapper').is(':visible'))
$(".field-group-format-toggler").click(function () {
$(".field-group-format-wrapper").css({'display':'none'});
});
... but that did not work either.
You can just use the toggle function:
$(".field-group-format-toggler").click(function()
{
$(".field-group-format-wrapper").toggle();
});
This will show the '.field-group-format-wrapper' elements if they are currently hidden and hide them if they're currently visible.
FYI the reason your code snippet in your question wasn't working is because you're only checking the visibility of the elements on dom ready, rather than on each click - so the event handler to show the elements will never be attached.
I guess your function is only being called on page load at which time all divs are hidden.
Why not check the visibility in the click event handler?
$('.field-group-format-toggler').click(function(){
var $wrapper = $('.field-group-format-wrapper'); //Maybe $(this).parent()?
if($wrapper.is(':visible'))
$wrapper.hide();
else
$wrapper.show();
As already mentioned, you can use the toggle function to achieve what you want.
To add a bit of extra information, when attaching events like you're doing, you're actually using a subscription model.
Registering an event puts it in a queue of events subscribed to that handler. In this case, when you add the second event to change the CSS, you're adding an event, not overwriting the first one.
Whilst thing isn't actually causing your problem, it's worth being aware of.

Google chrome, infinite loops and selecting text

This question comes with a bit of background. Please see two other questions I've recently posted that relate:
How to select text in a textbox cross-browser
Infinite loops created in google chrome
Word of warning: it's possible that the second link is a red herring.
Ok so my problem is that I'm trying to have it so when a user first clicks or tabs in to a textbox, all the text should become selected. If the textbox has focus, subsequent clicks on the text inside the textbox should behave normally (ie. doesn't re-select all the text). The answer I choose in the first link above is the one I found worked across all browsers. Code posted below for your convenience:
$('input[type="text"]').live('focus', function (event) {
var inp = this;
setTimeout(function () {
inp.select();
}, 1);
event.stopPropagation();
event.preventDefault();
return false;
});
Now my second link above is what I seem to be running in to with this approach. It seems that intermittently, google chrome gets stuck somewhere and starts changing the focus between textboxes really fast. You can see what I think is happening here: http://jsfiddle.net/ajbeaven/XppG9/14/
Like I said, it seems to be an intermittent problem so you might have to try reloading the page a couple of times in order to see what I think might be causing the changing of focus. Remember, it only seems to happen in chrome.
Thanks to anyone who can shed some light!
Put any additional work in the setTimeout function. And add a clearTimeout() before you setTimeout():
var focusTimeout = 0;
$('input[type="text"]').live('focus', function(event) {
var inp = this;
clearTimeout(focusTimeout);
focusTimeout = setTimeout(function() {
$('#message-container').html($('#message-container').html() + "*\u200b");
inp.select();
}, 1);
});
http://jsfiddle.net/XppG9/19/
In Chrome, writing the html to the page is (apparantly) causing the field to lose focus, and select() is causing it to receive focus 1ms later, thus triggering the focus event and causing the infinite loop. Moving the write html call into the function that selects the text seems to do the trick.
Oh man, I just figured it out. This bug probably won't happen to you on a real website. It's happening because you are updating the DOM adding a "*" to the message div. When you do this, it pushes the content of the page down. This moves the top text box to where the mouse is, and the mouseup event is triggered on the top text box, causing both text boxes to fire a setTimeout and getting in an infinite loop. Total dibs on reporting this.
edit: it's probably not the mouseup event. looks like chrome thinks you are legit focusing on both. Here's the bug test case for Chrome: http://jsfiddle.net/delvarworld/AnBE8/
edit2: This happens in Safari too. Most likely a webkit issue.
tldr simple workaround is to not update the dom in a way that causes reflow on the focus event, as in get rid of the html() line
You could also try:
$('input[type="text"]').live('mouseup', function (event) {
Which works in Chrome for me

Checking to see if a DOM element has focus

I've got a lightbox textbox that is displayed using an AJAX call from an ASP.NET UpdatePanel. When the lightbox is displayed, I use the focus() method of a textbox that is in the lightbox to bring focus to the textbox right away.
When in Firefox, the text box gains focus with no problem. In IE, the text box does not gain focus unless I use
setTimeout(function(){txtBx.focus()}, 500);
to make the focus method fire slightly later, after the DOM element has been loaded I'm assuming.
The problem is, immediately above that line, I'm already checking to see if the element is null/undefined, so the object already should exist if it hits that line, it just won't allow itself to gain focus right away for some reason.
Obviously setting a timer to "fix" this problem isn't the best or most elegant way to solve this. I'd like to be able to do something like the following:
var txtBx = document.getElementById('txtBx');
if (txtPassword != null) {
txtPassword.focus();
while (txtPassword.focus === false) {
txtPassword.focus();
}
}
Is there any way to tell that a text box has focus so I could do something like above?
Or am I looking at this the wrong way?
Edit
To clarify, I'm not calling the code on page load. The script is at the top of the page, however it is inside of a function that is called when ASP.NET's Asynchronous postback is complete, not when the page loads.
Because this is displayed after an Ajax update, the DOM should already be loaded, so I'm assuming that jQuery's $(document).ready() event won't be helpful here.
Try putting the javascript that sets focus at the end of the page instead of the beginning or having it fire after the page loaded event. That will help ensure that the DOM is completely loaded before setting focus.
I've used FastInit for this. JQuery $(document).ready() would also work.
You can try this:
Use the endRequest event of the PageRequestManager. That event fires once an Ajax update has finished.
Focus the textbox in the event handler
Here is some sample code:
<script type="text/javascript">
function onRequestEnd()
{
var txtBx = $get('txtBx');
txtBx.focus();
}
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(onRequestEnd);
</script>
To focus the textbox initially you can use the pageLoad function (shortcut to the load event of the Application client-side object):
<script type="text/javascript">
function pageLoad()
{
var txtBx = $get('txtBx');
txtBx.focus();
}
</script>
you could try something like this [IE Specific]. (untested)
theAjaxCreatedElement.onreadystatechange = function() {
if ( this.readyState != "complete" )
return;
this.focus();
};
Another way might be to change the background color of the element with onfocus, then retrieve it with js check if it is what it should be, if not: refocus the element.
It seems that IE does not update the DOM until after the script has finished running. Thus, a loop testing for focus will not allow the DOM to update. Using setTimeout is probably the only working solution.
Your example with .focus() is a well known example, see e.g. this answer.
Have you tried adding the autofocus="autofocus" attribute to the textbox element you are calling via Ajax?
Normally, when I need certain additional JavaScript functionality to run on dynamic content, I'll simply add that JavaScript to the content being called as well.
That JavaScript will also execute after it's added to the DOM. I don't see a point in writing JavaScript to your parent file and then "listening" for changes to the DOM. Like you mentioned, setTimeout() is more of a hack than anything else for something like this :)
There are several things in IE, that does the trick:
If focusing element has different z-index - you can quickly set z-index to that of currently focused element (possibly setting hidden attribute), set focus, and then set it back to original z-index.
Try to blur() currently focused element.
If element is 'shimmed' - focus the 'shim' element.

Categories

Resources