I have a Bootstrap 4 text field that I cannot give focus to. I have tried:
Clicking in the field
Using jQuery focus in console
Tabbing to it
Assigning autofocus attribute
When I look in chrome devtools Elements > EventListeners tab, go down to focus and remove the focus EventListeners, the field can get focus again. Also if I remove focusin listener it works.
I have tried in the console:
jQuery .off on the document object
$(document).off( "focusin");
jQuery .off on the window object
and
var customFunction = function (event) {
document.removeEventListener('focus',customFunction, false );
};
document.addEventListener("focus", customFunction, false);
Live Page
Here is what I mean about the devtools event listener screen
DevTools Screenshot with Annotation
Not really sure what to do next.
Thanks in advance.
This fixed the issue by removing jQuery's document.focus() EventListener which was blocking the input for some reason.
$btnSignContracts.on('click', function(e) {
$(document).off("focusin");
$(document).off("focus");
});
The field is working properly now.
Related
Using dot.js I'm adding a button to a specific web page that, when clicked, should add some text to a text field and then trigger another button to also be clicked. I simulate this by adding a click handler to my button which has this code:
var button = $('.some-class').find('button')[0];
console.log(button); // element I expect
button.click();
However, this doesn't work and I'm not sure why. If instead of .click() I perform .remove(), the button is removed from the page. If I use the console to execute the same code, the button does get clicked. This tells me I do have the right element, but there is something wrong with the click() event specifically.
Can someone explain why this isn't working in either Safari or Chrome? I've tried a lot of different things, but I'm new to jQuery so I'm probably missing some detail in how that works.
We went to the bottom of this in the chat. What probably caused the problem was another event-handler attached to (possibly) body, that undid the click.
So the solution was to stop the event from propagating:
event.stopPropagation();
While assigning the click event handler to the button you should use jquery on
This should ensure that whenever a new button with added with same selector (as in when event was assigned), event handled will be assigned to that button
Some examples here
The problem is the click() function is from jquery and you're attempting to fire the click function from the DOM object.
Try
$(button).click();
Here's a plunk.
http://plnkr.co/edit/2pcgVt
You can use the following statement.
var button = $('.some-class').find('button')[0].trigger('click');
try jquery's trigger() function:
$(button).trigger('click');
see jsfiddle: https://jsfiddle.net/665hjqwk/
I'm using Chrome DevTools to debug JavaScript. In my script I bound a click event to an element using the jQuery bind() method.
How to check if that event was fired or not?
Edit
Sorry because I wasn't so specific, I know that I can use console.log() or set a breakpoint inside the event listener body. What I'm talking about here is an out of box feature of the Chrome DevTools that allows you to check that without using the console, e.g a tab that contains all the events that were fired with related information.
Regarding Chrome, checkout the monitorEvents() via the command line API.
Open the console via Menu > Tools > JavaScript Console.
Enter monitorEvents(window);
View the console flooded with events
...
mousemove MouseEvent {dataTransfer: ...}
mouseout MouseEvent {dataTransfer: ...}
mouseover MouseEvent {dataTransfer: ...}
change Event {clipboardData: ...}
...
There are other examples in the documentation. I'm guessing this feature was added after the previous answer.
Use console.log() for more user friendly check (console must be opened of course to see the result):
$("#myElement").bind("click", function() {
console.log("Fired!");
});
Or you can alert it, which is much more anoying tho:
$("#myElement").bind("click", function() {
alert("Fired!");
});
You can try below code to check if event fire or not.
var eventFire = false;
$("button").on("click", function() {
eventFire = true;
if(eventFire){
alert('Event Fired')
}
});
I normally use an alert (because we develop on Rails -- console is unreliable):
$(document).on("event", "#element", function() {
alert("event");
});
The bottom line is you're going to have to trigger some "visible" thing to see if the event fired. If it doesn't, you'll either not be binding to the correct element, or your event won't be firing
Hope this helps!
Using jQuery Try the following:
$("#el").on("click", function() {
console.log("Fired!");
});
You can then see if the event was fired or not. So basically Just add a log in your function of where the event is triggering should do the trick.
You can put an "alert('message');" in your event handler and see a popup each time the handler fires.
Or you can put a "console.log('message');" in your event handler and review the log to see all the times that the event fired.
Or you can put "debugger" in your event handler and step through your code as it executes in the chrome debugger.
There is also a way to dynamically find an event handler and insert a debugger break point in your code using the chrome dev tools elements panel.
I'm trying to remove focus from a (jQuery Mobile) text input when a user switches tabs on desktop. While I can correctly identify the activeElement in the below console, I cannot edit any of its properties or remove its focus.
This is what I'm doing:
// inside some init method
window.onfocus = function () {
// triggers
console.log(document.activeElement);
if (document.activeElement.tagName !== "BODY") {
console.log("clear focus");
document.activeElement.blur();
document.activeElement.className = "FOOBAR";
}
};
When I'm on a form and focus a text input, then switch to another tab and go back to the tab with the form, the event listener triggers and my still active input is correctly logged. However that's it... I can't blur or edit any of the elements properties.
Question:
How do I correctly remove focus from the active element either on window.onfocus or window.onblur?
Thanks!
PS: it also does not work with jQuery:
$(window).on("focus", function () {
$(document.activeElement).blur();
});
and I'm looking for a JavaScript only solution.
EDIT:
document.activeElement.blur() works fine from the console, but not from my listener.
Ok. This works:
window.onblur = function () {
document.activeElement.blur();
};
So it seemed the blur worked fine, because if I console activeElemnt before and after my call to blur() it switched from an INPUT to the BODY tag. Correctly, my body has it's class set to FOOBAR. Problem for me was that the text element still retained focus, but I assume this is due to some handler inside jQuery Mobile.
The above solution works the other way around. I remove focus of the activeElement when the user switches a tab. Works.
I don't understand why the jQuery blur handler isn't working in the most simple case. I'm literally creating a div 100px by 100px and setting a blur event on it, but it's not firing (JSFiddle):
<div id="test">this is a test</div>
$(document).ready(function() {
$('#test').bind('blur', function() {
alert('blur event!');
});
});
Is my understanding of blur wrong? I expect the blur event to fire when I click anywhere that is not the div...right?
According to jQuery's documentation:
In recent browsers, the domain of the event has been extended to
include all element types. An element can lose focus via keyboard
commands, such as the Tab key, or by mouse clicks elsewhere on the
page.
I've tried it on the latest Chrome and Firefox on Mac.
From the W3C DOM Events specification:
focus
The focus event occurs when an element receives focus either via a pointing device or by
tabbing navigation. This event is valid for the following elements: LABEL, INPUT, SELECT,
TEXTAREA, and BUTTON.
blur
The blur event occurs when an element loses focus either via the pointing device or by
tabbing navigation. This event is valid for the following elements: LABEL, INPUT, SELECT,
TEXTAREA, and BUTTON.
The jQuery docs state browsers extended the events to other elements, which I'm guessing means blur and focus are aliases for the more generic DOMFocusIn and DOMFocusOut events. Non-input elements aren't eligible to receive those by default though, and an element has to somehow gain focus before losing it - a blur still won't fire for every click outside the div.
This SO question mentions that giving an element a tabindex would allow that, and seems to work for me in Chrome after modifying your jsFiddle. (Albeit with a fairly ugly outline.)
As far as I knew, blur happens on inputs that had the focus, either way you say
I expect the blur event to fire when I click anywhere that is not the div...right?
Not exactly, the blur event only happens for an element that had the focus first
So in order for a blur event to occur, you would first have to give focus to the div, how is the div getting focus first?
If you are really try to determine if there was a click outside of your div, you need to attach a click handler to the document, and then check to see where your click came from.
var div_id = "#my_div";
var outsideDivClick = function (event) {
var target = event.target || event.srcElement;
var box = jQuery(div_id);
do {
if (box[0] == target) {
// Click occured inside the box, do nothing.
return;
}
target = target.parentNode;
} while (target);
}
jQuery(document).click(outsideDivClick);
Just remember that this handler will be run for EVERY click on the page. (in the past if i ha to use something like this, i attach the handler when I need it, and remove it when I no longer need to look for it)
A can't "blur" because that would involve the div having focus in the first place. Non-input elements like a and textarea can have focus, which is what jQuery's documentation refers to.
What you need is the "mouseout" or "mouseleave" event (mouseleave doesn't bubble, mouseout does), which will be fired when the cursor leaves the div. If you need to have clicks, I would attach a "click" event to the body, as well as the div and stopping the event propagation on only the div:
$("div").click(function(e) {
return false; // stop propagation
});
Or, if you're really determined, you can fake the appearance of a div with a and some CSS rules :)
If you want something to happen while you move your mouse over the box, you could use the mouseover event.
I have a form to upload files, and it should fire the submit after the file selection.
On FireFox/Chrome it goes well, and submits the form after file selection, but I can't do this on Internet Explorer.
Already tried with click/propertychange but nothing happens. Some code I already tried:
$("#attach").attr("onChange", "alert('I changed')");
$("#attach").live($.browser.msie? 'propertychange': 'change', function(e) { ... });
This input file is created on the fly; because of it I use .live() to bind the event.
Any suggestions?
I know this is several months late, but I just ran into the exact same behavior in IE7; in all other browsers, the change event for file inputs happens after file selection. In IE7, it happens only if you trigger the file select again, or on blur.
Here's how I ended up fixing it:
var $input = $('#your-file-input-element');
var someFunction = function()
{
// what you actually want to do
};
if ($.browser.msie)
{
// IE suspends timeouts until after the file dialog closes
$input.click(function(event)
{
setTimeout(function()
{
if($input.val().length > 0) {
someFunction();
}
}, 0);
});
}
else
{
// All other browsers behave
$input.change(someFunction);
}
Technically you could/should filter the hack condition to just IE7, since IE8 behaves properly on the change event, but it also has the same behavior as IE7 on suspending timeouts while browser-related chrome is visible (I guess it considers it blocking I/O), so it works as-is.
This is really late, but I was having the same problem, and I solved it by using a styled <label> tag with a slight workaround for Firefox.
http://jsfiddle.net/djibouti33/uP7A9/
The Goals:
allow user to upload a file by using standard html file input control
hide standard html file input control and apply own styling
after user selects file to upload, automatically submit the form
The Browsers:
Firefox, Chrome, IE8/9, Safari
IE7 didn't work, but it might if you add that browser to the workaround detailed at the bottom
The Initial Solution:
Hide the file input by positioning it offscreen. Important not to display:none as some browsers won't like this.
Add another styled element to the page (link, button).
Listen for a click on that element, then programmatically send a click to the file input to trigger the native 'file explorer'
Listen for the file input's onchange event (occurs after a user chooses their file)
Submit the form
The Problem:
IE: if you programmatically send a click to a file input in order to activate it (2), programmatically submitting the form (5) will throw a security error
The Workaround Solution:
Same as above
Take advantage of the accessibility features built in to the tag (clicking on a label will activate it's associated control) by styling
a tag instead of a link/button
Listen for the file input's onchange event
Submit the form
For some reason Mozilla browsers won't activate a file input by clicking on it's .
For Mozilla, listen for the click on the label and send a click event to the file input to activate it.
Hope this helps! Check out the jsfiddle for details on the html/js/css used to make it all work.
Format it like this:
$("#attach").change(function() {
alert('I Changed');
});
Update: After answering another question on this earlier, we realized this was fixed as part of the jQuery 1.4.2 event re-write, just update to the latest version to resolve the change event issue with <input type="file" /> in IE.
I used the following solution. I tried to make it as self-contained as possible.
(function($) {
if ($.browser.msie == false)
return;
$('input[type=file]').live('click', function(e) {
var self = this;
var blur = function() {
$(self).blur();
}
setTimeout(blur, 0);
});
})(jQuery);
This has always worked for me in IE6 ad IE7.
$('#id-of-input-type-file').change(function(){});
In IE onchange event works fine when it filled out in html tag directly. Like:
<input type="file" onchange="uploader.upload()" />
This is likely a problem with a race condition with input fields in IE. By using setTimeout the function that is executed will then register that a change happened. When the UI code is performed in the onChangeEvent, that event hasn't fired yet as it appears to IE.
I solved a similar situation by doing the following inside my change handler:
if (jQuery.browser.msie) { setTimeout(DoSomeUIChange, 0); } else { DoSomeUIChange(); }
The DoSomeUIChange is executed after the current code on the event queue and so removes the race condition.
I was having the same issue with IE (including IE 9). The UI logic is:
click on a div element triggers the click event on a file-input-element so that user click on a div trigger file open dialog
bind the change event handler to the file-input-element to ensure the form is submitted when file open dialog closed
The app (running inside an iframe) works like a charm on Chrome and FF. But soon I found it doesn't work on IE as when user selected a file and close the dialog the form didn't submit.
The final solution is to drop the logic #1 "click on div element trigger click event on file input element" and let user to click on the file input element directly, and then it works.
BTW, the reason we have a div element is we want to hide the browser rendered controls because we have everything in the background image. However set display to none makes the control not able to respond a user interaction event. So we move the file-input-element to outside of the view port and use a div element to replace it. Since this doesn't work on IE, we end up with move back the file-input-element and set it's opacity to 0. On IE 8 or less which doesn't support opacity, we use filter to make it transparent:
#browse {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=0);
filter: alpha(opacity=0);
-ms-filter: "progid:DXImageTransform.Microsoft.Alpha(Opacity=0)";
}
I found this solution
In HTML hide file element (don't use display: none, won't work in IE), prepare onchange event of IE:
<div style="width: 0px; height: 0px; overflow: hidden;">
<input id="ifile_template" type="file" onchange="this.focus(); this.blur();"/>
</div>
In javascript for IE bind function to blur, and for FF,CH bind function change():
$(iFile).blur(
function () {
...some code...
}
);
// FF, CH
$(iFile).change(
function () {
...some code...
}
);
For IE You can use the "onfocus" event to catch the change of uploading file. Once the file browsing dialog is closed the onfocus event is triggered. You can check this by adding this line to your page:
<input type="file" onfocus="javascript:alert('test');" />
Once the dialog is closed the alert message is shown.
This solution is only for IE, not for FF or Chrome.
My solution:
setInterval(function()
{
if ($.browser.msie) $("input[type=file]").blur();
},500);
Not pretty, but it works. ;D
I can confirm, at least that it only works after a blur event takes place, similar to a radio and checkbox in IE. I am probably going to have to add some kind of visual element for the user to click and tell me when they have picked their file.
lame.
$("#attach").attr("onChange", "alert('I changed')");
It works in IE, but if you want to emulate "live" behavior, you should add "onChange" attribute to each new element when create its.
jQuery doesn't seem to recognise the propertychange event. I added it to the DOM node using IE's attachEvent().
var userChoseFile = function($input) {
// ...
}
var $input = $(/* your file input */);
$input[0].attachEvent('onpropertychange', function() {
userChoseFile($input);
});
Look at these fiddle http://jsfiddle.net/uP7A9/531/
HTML:
<input type="file" name="PicturePath" id="fileUpload" accept=".png,.jpg,.jpeg,.gif,.tif" />
jQuery:
$("input[type=file]#fileUpload").on("change", function () {
alert('hi')
});
it works for all browsers, tested.