Detect if button click real user or triggered by a script - javascript

Is there any method that enables me to detect whether a button click was performed by a real user and not some automated method (javascript) that a user has loaded onto their browser developer console or other browser developer tool?
I tried the following methods suggested in various stackoverflow posts but none of them appear to work.
REF: How to detect if a click() is a mouse click or triggered by some code?
Script Detection methods tried and failed:
mybutton.click(function (e) {
if (!e.which) {
//Triggered by code NOT Actually clicked
alert(' e.which - not a real button click')
} else if ('isTrusted' in e && !e.isTrsuted) {
//Triggered by code NOT Actually clicked
alert(' e.isTrusted - not a real button click')
} else if (e.originalEvent === undefined) {
//Triggered by code NOT Actually clicked
alert(' e.originalEvent - not a realbutton click')
}
// else if (!e.focus) {
// //triggered // does not detect e.focus on a real btn click
// alert(' e.focus - not a realbutton click')
// }
else {
// Button hopefully clicked by a real user and not a script
}
})
If I run the following script to trigger the button click from the Chrome browser console none of the methods above traps it as being triggered by a script.
var button = document.getElementById("btnSubmit");
button.click();
==========================================================================
Thank you for all your responses and thanks to stackoverflow for providing such a great site that facilitates so much knowledge sharing and for saving us techies an untold number of hours.
It appears that I still do not have reliable method. All 3 browsers (FF, IE & Chrome) provide a developer/console interfaces for a user to run/inject a javascript on my webpage. It appears that each browser flavor traps some event property values a little differently. For example: Chrome traps the difference between a script activated cick and a real user with e.screenX but in IE: e.screenX has the same value for both a script click (synthetic) and a user button click
The following detection methods either did not work at all or are inconsistent across the different browsers: e.which e.isTrsuted e.originalEvent (event.source != window) (e.distance != null)
The mousedown event appears to be only triggered by a real user button click, but I have to assume there is some script method to emulate a mousedown in addition to a button click event
$(me.container + ' .mybutton').mousedown(function (e) {
alert('mouseisdown real button click');
}
If anyone can figure out a reliable method that works across multiple browsers, that detects the difference between a synthetic (script) button click and a button click by a user, you will deserve superhero status.

when a button click happens through the mouse, the event e usually has the mouse pointer location recorded. Try something like :
if(e.screenX && e.screenX != 0 && e.screenY && e.screenY != 0){
alert("real button click");
}

No, it's not possible in all cases.
As other answers mentioned, you can look for the mouse coordinates (clientX/Y and screenX/Y), and if they're not present, you can assume it was probably not a human-generated action.
But, if the user tabs onto the button and uses the space bar to click it, or otherwise clicks it without using a mouse, the coordinates will also be zero, and this method will incorrectly determine it to be a scripted click.
Also, if the script uses dispatchEvent instead of click, coordinates can be given to the event. In this case, this method will incorrectly identify it as a user-generated click.
// This will produce what appears to be a user-generated click.
function simulateClick(element) {
var evt = document.createEvent("MouseEvents");
evt.initMouseEvent("click", true, true, window,
0, 110, 111, 10, 11, false, false, false, false, 0, null);
element.dispatchEvent(evt);
}
http://jsfiddle.net/bYq7m/

For security purposes when you trigger an event with javascript it will register differently than if the user triggered the event. Console log the ev object and you will see significant differences between the two cases.
mybutton.click(function(ev) {
console.log(ev);
});
Here are some sample output of the two cases:
jQuery.Event
currentTarget: button
data: null
delegateTarget: button
handleObj: Object
isTrigger: true
jQuery191011352501437067986: true
namespace: ""
namespace_re: null
result: undefined
target: button
timeStamp: 1360472753601
type: "mousedown"
__proto__: Object
jQuery.Event {originalEvent: MouseEvent, type: "mousedown", isDefaultPrevented: function, timeStamp: 1360472840714, jQuery191011352501437067986: true…}
altKey: false
bubbles: true
button: 0
buttons: undefined
cancelable: true
clientX: 39
clientY: 13
ctrlKey: false
currentTarget: button
data: null
delegateTarget: button
eventPhase: 2
fromElement: null
handleObj: Object
isDefaultPrevented: function returnFalse() {
jQuery191011352501437067986: true
metaKey: false
offsetX: 37
offsetY: 11
originalEvent: MouseEvent
pageX: 39
pageY: 13
relatedTarget: null
screenX: 1354
screenY: 286
shiftKey: false
target: button
timeStamp: 1360472840714
toElement: button
type: "mousedown"
view: Window
which: 1
__proto__: Object

Use "event.isTrusted" to know event is triggered from Javascript or User click.
Sample Code:
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="text" id="myInput">
<button id="myBtn" onclick="callFunction(event)">Click Me</button>
<script>
function callFunction(event) {
console.log(event.isTrusted); // true only when user clicks 'Click Me' button
}
window.onload = function () {
let event = new Event("click");
callFunction(event); // false
}
var input = document.getElementById("myInput");
// Execute a function when the user releases a key on the keyboard
input.addEventListener("keyup", function (event) {
if (event.keyCode === 13) {
event.preventDefault();
document.getElementById("myBtn").click(); // false
}
});
</script>
</body>
</html>

Fiddle Here.
$("button").mousedown( function(e) {
if(e.which) {
alert(1);
}
});
$("button").trigger("mousedown");
Or Javascript:
document.getElementsByTagName('button')[0].onmousedown = function(e) {
if(e.which) {
alert(1); // original click
}
}
document.getElementsByTagName('button')[0].onmousedown();
You can see in the fiddle, it will not let trigger function to call but only when mouse is down on button. If automated click is triggered on button then e.which is undefined which can be trapped easily.
UPDATE : Fiddle For Javascript

Event object have a nativeEvent object which contains isTrusted field.
Its value will be false when event is not triggered by real user.
So you can check if real user clicked the button by -
if(event.nativeEvent.isTrusted){
//Real user
} else {
//Triggered by script
}

Related

How to make one NOT be able to simulate a click

I've noticed while working for someone on a script that this special button ( the login one ): https://www.easports.com/fifa/ultimate-team/web-app/ does not allow to simulate a click on it in any possible way.
I'm extremely curious to know how they do it.
I've tried
var btn=$('#Login > div > div > button.btn-standard.call-to-action');
btn.click(); // or trigger('click');
// or
click = new Event(click);
btn.dispatchEvent(click);
// or
btn.trigger('mousedown');
// oh and also:
function click(x, y)
{
var ev = new MouseEvent('click', {
'view': window,
'bubbles': true,
'cancelable': true,
'screenX': x,
'screenY': y
});
var el = document.elementFromPoint(x, y);
el.dispatchEvent(ev);
}
I've even tried mouseenter, followed by mousedown and mouseup;
How can one achieve this sort of feature?
Here's an example of what they might be doing. Event.isTrusted gives you information on if it was a user action or a created event. They probably have some logic around this:
From the docs:
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
EventTarget.dispatchEvent().
document.getElementById('btn').addEventListener('click', (e) => console.log(e.isTrusted));
// Simulate a click onload (should print false to the console)
document.getElementById('btn').click(); // false
// TODO: Click the Button manually, you should see 'true' being printed
<button id="btn">Button</button>
My guess is that if you look into their source code, you'd see something similar where they are just doing an .stopPropogation or .preventDefault if isTrusted is false.
So they are probably doing this:
document.getElementById('btn1').addEventListener('click', (e) => {
if (!e.isTrusted) { e.preventDefault(); return;}
console.log('Button clicked!');
});
document.getElementById('btn1').click(); // nothing printed to console.
<button id="btn1">Button</button>

Mysterious mouse event closes jQuery UI dialog

This is obviously a SSCCE.
So we are tasked with writing the front-end of a missile launch control system. We opt for a Spartan layout given that this is deadly serious: just a text input box and a button to enter the code:
For safety purposes, upon clicking on the "OK" button we will display a dialog asking the user to confirm:
As a usability finishing touch we add a key listener for the Enter button that will also result in clicking the "OK" button (using $.trigger()).
Unfortunately, the confirmation dialog is only displayed when the user clicks on the "OK" button but not when hitting Enter. When we hit Enter the dialog does not appear at all.
Worst still, after adding some debugging messages it appears that the dialog is indeed displayed for a fraction of a millisecond and then for some reason the "Yeap" button is clicked. So when Enter is hit, missile launch is immediately confirmed!
Fiddle here.
Code below:
function inputKeyListener(evt) {
console.log('key listener - triggered key code is: ' + evt.keyCode);
if (evt.keyCode === $.ui.keyCode.ENTER) {
evt.stopPropagation();
$('#missile-launch-button').click(); // Directly calling confirm() doesn't work either
}
}
function missileLaunchButtonClickHandler(e) {
e.stopPropagation();
confirm();
}
function confirm() {
var launchCode = $('#missile-launch-code-input').val();
const dialog = $('#missile-launch-confirmation-modal');
dialog.dialog({
closeOnEscape: false,
dialogClass: 'no-close',
open: function(event, ui) {
console.log('confirm :: open is called');
},
close: function() {
console.log('confirm :: close is called');
},
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Yeap": function() {
console.log('Confirmation button was clicked');
$(this).dialog("close");
console.log('missile launch with code [' + launchCode + '] was confirmed!');
},
"Maybe not just yet": function(ev) {
console.log('Abort button was clicked');
$(this).dialog("close");
console.log('Armageddon was averted');
}
}
});
dialog.dialog('open');
console.log('by this time the dialog should be displayed');
}
$('#missile-launch-confirmation-modal').dialog({
autoOpen: false
});
$('#missile-launch-button').click(missileLaunchButtonClickHandler);
$(document).on('keydown', inputKeyListener);
<link rel='stylesheet' href='https://code.jquery.com/ui/1.11.4/themes/vader/jquery-ui.css'>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div id='missile-launch-confirmation-modal' title='Confirm missile launch' </div>
<span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span> Are you sure you want to unleash nuclear Armageddon?
</div>
</div>
<div>
<div>
<div>Enter missile launch code:</div>
<div>
<input id='missile-launch-code-input' type='text' autofocus/>
</div>
<div>
<button id='missile-launch-button' type='button'>OK</button>
</div>
</div>
</div>
Update
In the code above the inputKeyListener is bound to keydown on document. Binding it more narrowly to the keydown on the text input, as in:
$('#missile-launch-code-input').on('keydown', inputKeyListener);
… results in the exact same behavior.
Update II
This answer suggests that stopPropagation is ineffective here because "event bubbling isn't really in play here" and explains that preventDefault should be used to "[stop] the key event from reaching other page elements (i.e. that button)". I am a bit confused with those two statements taken together. I thought that stopPropagation is precisely what one uses to stop a "key event from reaching other page elements". Moreover there are two further points of confusion.
The first point of confusion is that the confirmation dialog div is not a parent DOM element of the text input div, so it is unclear how a keyboard event at the text input div is intercepted by a sibling (not parent) DOM element. I think this is in fact the reason that stopPropagation is ineffective but still it's not clear to me why (regardless of stopPropagation) the event reaches the confirmation dialog button which lies in a sibling div.
The second point of confusion is that if we log the event we capture in the "Yeap" button function handler, e.g. like this:
buttons: {
"Yeap": function(ev) {
console.log(ev);
… what we in fact see in the console is:
… so it is a mouse event, not a keyboard event that confirms the dialog. Given that (in the scenario where one simple hits Enter) the only mouse event we are generating is in the inputKeyListener:
$('#missile-launch-button').click();
… this means that it is this event that results in the confirmation of the dialog, not the keyboard event we get by hitting Enter
This appears to be a case of jQuery UI being slightly too helpful for its own good: when a dialog opens, it puts the first button inside it into focus, just in time for the "enter" key event to trigger the button (which is the browser's default behavior when the user hits "enter" while a button is in focus.)
Using preventDefault in your inputKeyListener stops the key event from reaching other page elements (i.e. that button). stopPropagation is harmless but will have no useful effect in either inputKeyListener or missileLaunchButtonClickHandler because event bubbling isn't really in play here.
Here's a demo with no preventDefault or stopPropagation, and a dummy button included to harmlessly catch the autofocus, just to confirm that this is what's happening:
function inputKeyListener(evt) {
console.log('key listener - triggered key code is: ' + evt.keyCode);
if (evt.keyCode === $.ui.keyCode.ENTER) {
// $('#missile-launch-button').click(); // Directly calling confirm() doesn't work either
confirm(); // Does too!
}
}
function missileLaunchButtonClickHandler(e) {
confirm();
}
function confirm() {
var launchCode = $('#missile-launch-code-input').val();
const dialog = $('#missile-launch-confirmation-modal');
dialog.dialog({
closeOnEscape: false,
dialogClass: 'no-close',
open: function(event, ui) {
console.log('confirm :: open is called');
},
close: function() {
console.log('confirm :: close is called');
},
resizable: false,
height: "auto",
width: 400,
modal: true,
buttons: {
"Hmmmm": function() {
console.log('First button inside the dialog was clicked.');
},
"Yeap": function() {
console.log('Confirmation button was clicked');
$(this).dialog("close");
console.log('missile launch with code [' + launchCode + '] was confirmed!');
},
"Maybe not just yet": function(ev) {
console.log('Abort button was clicked');
$(this).dialog("close");
console.log('Armageddon was averted');
}
}
});
dialog.dialog('open');
console.log('by this time the dialog should be displayed');
}
$('#missile-launch-confirmation-modal').dialog({
autoOpen: false
});
$('#missile-launch-button').click(missileLaunchButtonClickHandler);
$(document).on('keydown', inputKeyListener);
<link rel='stylesheet' href='https://code.jquery.com/ui/1.11.4/themes/vader/jquery-ui.css'>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.min.js"></script>
<div id='missile-launch-confirmation-modal' title='Confirm missile launch' </div>
<span class="ui-icon ui-icon-alert" style="float:left; margin:12px 12px 20px 0;"></span> Are you sure you want to unleash nuclear Armageddon?
</div>
</div>
<div>
<div>
<div>Enter missile launch code:</div>
<div>
<input id='missile-launch-code-input' type='text' autofocus/>
</div>
<div>
<button id='missile-launch-button' type='button'>OK</button>
</div>
</div>
</div>
on event.preventDefault vs event.stopPropagation
To expand on this, per "Update II": stopPropagation prevents events bubbling up to parent DOM nodes. Normally, for example, click events bubble upwards from the node directly clicked on through every parent node.
The reason stopPropagation is irrelevant here is because dialog is not a parent of the input element: event bubbling wouldn't have reached dialog. So there's no reason to stop the event bubbling with stopPropagation, because it wouldn't have triggered anything meaningful anyway.
The events stopped by event.preventDefault, by contrast, have nothing to do with the DOM structure -- these events don't care if parent, sibling, grandchild, or third cousin twice removed; event.preventDefault simply means "whatever the default behavior of the browser would have been in this situation, don't do that." So event.preventDefault on a form submit stops the form being submitted, for example.
In the case described in this question, the default browser behavior if the user hits the "enter" key while a button is in focus is to trigger a click event (which is, yes, a mouse event) on that button, regardless of where the button is in the DOM. So using event.preventDefault here prevents that default behavior, which is what you want.
At first, you need to call the missileLaunchButtonClickHandler inside your inputKeyListener function.
After you need to add a "preventDefault" to your missileLaunchButtonClickHandler function because the dialog is closing automatically when you hit ENTER. The preventDefault avoid the dialog to close automatically.
Change your missileLaunchButtonClickHandler function to this:
function missileLaunchButtonClickHandler(e) {
//e.stopPropagation();
e.preventDefault();
confirm();
}
and modify your inputKeyListener to this:
function inputKeyListener (evt) {
console.log('key listener - triggered key code is: '+evt.keyCode);
if (evt.keyCode === $.ui.keyCode.ENTER) {
evt.stopPropagation();
missileLaunchButtonClickHandler(evt);
$('#missile-launch-button').click(); // directly calling confirm() doesn't work either
}
}

How do I fire from a <button> CTRL+V and CTRL+Z to a targeted <textarea>?

I want to fire from a button Ctrl+V and Ctrl+Z to a targeted textarea. If it is possibility to have this as an onclick button instead of id button that would be perfect. How do I do that?
NOTE: Please do not misunderstand this post with detecting or alert keypress. I do NOT want that. I want to have a button that executes this keypress onto the textarea.
My JavaScript:
<script type="text/javascript">
var t = document.getElementById('mytextarea'),
bcsv = document.getElementById('bcv'),
bsz = document.getElementById('bcz'),
cv = document.createEvent('KeyboardEvents'),
cz = document.createEvent('KeyboardEvents');
cv.initKeyboardEvent(
'keydown',
true, // key down events bubble
true, // and they can be cancelled
document.defaultView, // Use the default view
true, // ctrl
false, // alt
false, //shift
false, //meta key
86, // keycode
0
);
cz.initKeyboardEvent(
'keydown',
true, // key down events bubble
true, // and they can be cancelled
document.defaultView, // Use the default view
true, // ctrl
false, // alt
false, //shift
false, //meta key
90, // keycode
0
);
bcz.addEventListener('click', function(){
t.dispatchEvent(cz);
}, false);
bcsz.addEventListener('click', function(){
t.dispatchEvent(csz);
}, false);
</script>
My HTML:
<input type="button" value="CTRL+V" id="bcv" />
<input type="button" value="CTRL+Z" id="bcz" />
<textarea id="mytextarea" rows="5" cols="10"></textarea>
Question: I never managed to make this work. So how do I make it work? Or is it another way to make this work?
How do I make two buttons to act as if I would push Ctrl+V and Ctrl+Z on the keyboard on a targeted textarea? But without using the keyboard.

Detect jquery reveal plugin modal close by esc key or clicking outside

I am using jquery reveal plugin for showing pop-up. I am looking for a way in jquery or javascript by which I can trigger an appropriate event when that popup was closed by pressing esc key or clicking outside of pop-up. Is there any way by which I can capture this event?
And on reveal plugin website only few options are given, like:
$('#myModal').reveal({
animation: 'fadeAndPop', //fade, fadeAndPop, none
animationspeed: 300, //how fast animtions are
closeonbackgroundclick: true, //if you click background will modal close?
dismissmodalclass: 'close-reveal-modal' //the class of a button or element that will close an open modal
});
Are there any more options for this plugin? If so, please provide me link for that.
According to the source an Event called 'reveal:close' is fired in both cases and you should be able to add your own handler for that event through
$yourModal.bind('reveal:close', function () {
console.log('Modal closed');
});
When you need to know in which way it was closed you could use the 'reveal:open' event to add either a keyup event handler on the document-object or a click event handler on the .reveal-modal-bg element.
$yourModal.bind('reval:open', function () {
var $document = $(document);
$document.bind('keyup', function onEscHandler( event ) {
if (event.which === 27) {
console.log('closed by ESC');
// Modal is closed, let's remove the handler again
$document.unbind('keyup', onEscHandler);
}
});
var $modal_bg = $('.reveal-modal-bg');
$modal_bg.one('click', function onBgClidkHandler() {
console.log('closed by click on BG');
// We don't need to remove this handler since 'one' does it automatically.
});
});
Open jquery.reveal.js.
Add new option:
var defaults = {
animation: 'fadeAndPop',
animationspeed: 300,
closeonbackgroundclick: true,
dismissmodalclass: 'close-reveal-modal'
escape: true // true: modal close with Esc. false: modal no close with Esc
};
In the file jquery.validate, find the line that content e.which===27.
Complete line is:
if(e.which===27){ modal.trigger('reveal:close'); }
Modify and validate new option escape in this line:
if(e.which===27 && options.escape === true){
modal.trigger('reveal:close');
}
That's it. Now the escape option works.

jquery-ui Dialog: Make a button in the dialog the default action (Enter key)

In a jquery modal dialog, is there a way to select a button as the default action (action to execute when the user presses enter)?
Example of jquery web site:
jquery dialog modal message
In the example above the dialog closes when the user presses Esc. I would like the "Ok" button action to be called when the user presses Enter.
In your dialog's open function, you can focus the button:
$("#myDialog").dialog({
open: function() {
$(this).parents('.ui-dialog-buttonpane button:eq(0)').focus();
}
});
Change the :eq(0) if it's at a different index, or find by name, etc.
I like this one (it is working for me), which leaves the focus where I wanted to be (a text box)
$("#logonDialog").keydown(function (event) {
if (event.keyCode == $.ui.keyCode.ENTER) {
$(this).parent()
.find("button:eq(0)").trigger("click");
return false;
}
});
However, this is working just for one button (Ok button), if needed ':eq(n)' could be set to select other button.
Note: I added a new line returning false to prevent event bubbling when the enter key is handled, I hope it helps better than before.
try this way:
$("#myDialog").dialog({
open: function() {
$(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus();
}
});
This other stackoverflow question should get you where you want:
$('#DialogTag').keyup(function(e) {
if (e.keyCode == 13) {
//Close dialog and/or submit here...
}
});
Another option that gives you more control over all buttons in the dialog is to add them as an array of buttons. Then in the open event you can get the buttons by id and do whatever you want (including set the focus)
$('#myDialog').dialog({
buttons: [
{
id: "btnCancel",
text: "Cancel",
click: function(){
$(this).dialog('close');
}
},
{
id: "btnOne",
text: "Print One",
click: function () {
SomeFunction(1);
}
},
{
id: "btnTwo",
text: "Print Two",
click: function(){
SomeFunction(0);
}
}
],
open: function () {
if ($('#hiddenBool').val() != 'True') {
$('#btnOne').hide();
}
$("#btnTwo").focus();
}
});
A slight variation to use the buttons name as the selector. It reads a little better but there is obvious duplication with the button text string. Refactor to taste.
$("#confirm-dialog").dialog({
buttons: {
"Cancel" : function(){},
"OK" : function(){}
},
open: function() {
$(this).siblings('.ui-dialog-buttonpane').find("button:contains('OK')").focus();
}
});
The simplest way would be to use the submit action on a form within the dialog, however:
I did not want to require a form within dialog (N.B. different browsers handle the enter key differently, and some do not always do a submit on enter).
I wanted this to work if the user clicks in the title pane or button pane prior to pressing enter.
I wanted to make a library method that I can use for ANY
jQueryUI dialog.
The company I work for is 'EBL' and I avoid global scope...hence the prefix on the functions below:
EBL.onUiDialogOpen = function (event, ui, hideX, actionFirstButtonOnEnterKey) {
if (hideX) {
// There is no option to hide the 'X' so override.
$(".ui-dialog-titlebar-close").hide();
}
if (actionFirstButtonOnEnterKey) {
/* (event.target) will give the div that will become the content
of a UI dialog, once div is 'opened' is it surrounded by a
parent div that contains title and buttonpane divs as well as
content div - so I use .parent()
...The keyup function is binded to all descendants, therefore:
-We need the e.stopPropagation() line.
-This code is NOT what you want if you DON'T want enter
key to initiate first button regardless of selected control.
*/
$(event.target).parent().bind('keydown.justWhileOpen', function (e) {
if (e.keyCode === $.ui.keyCode.ENTER) {
e.stopPropagation();
$(event.target).next('.ui-dialog-buttonpane')
.find('button:first').click();
}
});
}
};
...works in combination with:
EBL.onUiDialogClose = function (event, ui) {
// Remove keyup handler when we close dialog
$(event.target).parent().unbind('.justWhileOpen');
};
You do not need the .onUiDialogClose if you are using a dynamically created div and destroying it afterwards.
You can see below how I use these library functions when initialising a non-dynamic dialog...
$('#divName').dialog({
//...
open: function (event, ui) { EBL.onUiDialogOpen(event, ui, false, true); },
close: function (event, ui) { EBL.onUiDialogClose(event, ui); },
//...
});
So far I have tested this in IE9 and latest chrome/firefox.
You should validate the dialog as neccessary in your 'Ok' function.
I'm using version 1.10.0. I could not get it to work with open but with focus. This focuses the second button:
focus: function(){
$(this).siblings('.ui-dialog-buttonpane').find('button:eq(1)').focus();
}
$("#logonDialog").keydown(function (event) {if (event.keyCode == 13) {
$(this).parent().find("button:eq(0)").trigger("click");
return false;
}
});
This worked for me within the dialog using jquery 1.10.2
dialog({
focus: function() {
$(this).on("keyup", function(e) {
if (e.keyCode === 13) {
$(this).parent().find("button:eq(1)").trigger("click");
return false;
}
});
},
more options...
This simple piece of code styles your buttons and sets the default to the last one:
open: function(){
$buttonPane = $(this).next();
$buttonPane.find('button:first').addClass('accept').addClass('ui-priority-secondary');
$buttonPane.find('button:last').addClass('cancel').addClass('ui-state-default');
$buttonPane.find('button:last').focus();
},
In my case, none of the answers worked because I called .dialog on an empty div and added my buttons dynamically, so the $(this).html() would return nothing. So I couldn't call methods like parent() or siblings() and expect something in return. What I did was select the ui-dialog-buttonpane class directly and find the button element from there
HTML
<div id = "dialogexample">
</div>
Jquery
$("#dialogexample").dialog({
autoOpen: false,
modal: true,
open: function () {
$('.ui-dialog-buttonpane').find('#otherbutton').focus();
}
});
var buttons = {
"MyButton" : {
text: "Do Stuff",
id: "dostuffbutton"
},
"OtherButton" : {
text: "Other Stuff",
id: "otherbutton"
}
}
$("#dialogexample").dialog("option", "buttons", buttons);
$("#dialogexample").dialog("open"); //the second (otherbutton), instead of
//the first (dostuffbutton) button should be focused
I know this is an old thread, but I was searching for this exact functionality and was able to implement what I think is the best solution as I found all of the above to fall short a little.
It is a combination of two answers above. Using an ID rather than relying on the find() function to find the button element always seems to be a much better choice to me.
Also explicitly looking for the enter key to be pressed allows us to set focus to whatever element we want when the dialog is opened if desired. This just seems to allow for the most flexibility while satisfying the desire of triggering a specific button as 'default' when the enter key is pressed. I have also implemented a 'cancel' default as well.
I hope this helps others looking for a good 'default' button solution for dialogs.
$("#LoginBox").dialog({
open: function(){
$(this).keydown(function (event) {
if (event.keyCode == 13) {
$("#LogInButton").trigger("click");
return false;
}
if (event.keyCode == 27) {
$("#CancelButton").trigger("click");
return false;
}
});
},
close: function(){
$(this).dialog("destroy");
},
buttons: [
{
id: "LogInButton",
text: "Log In",
click: function(){
//button functionality goes here
$(this).dialog("destroy");
}
},
{
id: "CancelButton",
text: "Cancel",
click: function(){
$(this).dialog("destroy");
}
}
]
});
You should to use :tabbable selector and index of your button (0 is [X] button, yours started from 1)
open: function() {
var tb = $(":tabbable", this.parentNode);
if(tb.length>1) {
tb[1].focus();
}
}

Categories