I need to trigger the click, on click on my webpage. I tried the below and it triggers the click onload and not on click.
$(function() {
$("body").click(function(e) {
alert("code");
})
$('#container').trigger('click');
});
Basically I need to show a popup on click of P keyword from keyboard. While I started I got stuck during the initial stages. Not sure how to achieve this.
I guess you need a keydown event where P key passes ASCII code 80:
$("body").on("keydown", function(e) {
if (e.which === 80) {
alert("'p' was pressed");
}
});
Related
I have a notification dropdown similar to what stackoverflow has. So when the user request the notifications window I open and close my dropdown div using .show and .hide.
Meanwhile I also want to close it when the user clicks anywhere outside my dropdown div.
My approach was to do the following on my layout.cshtml :
$(document).on("click", onDocumentClick);
function onDocumentClick(event) {
var target = $(event.target);
if (!target.hasClass('nbr-notifications')) {
if ($('#notifications-dropdown').css('display') === 'block') {
$('#notifications-dropdown').hide();
}
}
}
My question and concern is : Is this the best way to do it? From the performance perspective? Since I am handling all clicks on my document everytime.
Couldn't you use this if you are not sure where the element would be?
$('body').on("click",".nbr-notifications", onClick)
.on('blur','.nbr-notifications',closeNotifications);
function onClick(event) {
if ($('#notifications-dropdown').css('display') === 'block') {
$('#notifications-dropdown').hide();
}
}
function closeNotifications()
{
//close it
}
Here only responding to clicks on elements with the class 'nbr-notifications' rather than hooking event handler for all clicks and check if the target is the required one.
If you want the notification to disappear after it loses focus why not just bind a focusout event specifically to that element instead of click to the entire document.
http://api.jquery.com/focusout/
$('.nbr-notifications').on('focusout',function(){
//close functionality here. something like: $(this).hide();
});
When a user opens dialog, there are a bunch of ajax requests that have to be processed and therefore i have a second dialog that just displays loading information and closes once all the requests have been processed.
I am not able to close the user opened dialog with Escape key once it has opened. I have to click on the the dialog itself before I can use escape.
I have tried the following to assign the user opened dialog the focus after the loading dialog closes but to no avail, I still have to click on the dialog before it can close with the escape key.
$(document).ajaxStart(function () {
// IF loading dialog is not allready being shown show it.
if ($("#LoadingData").dialog('isOpen') === false) {
$("#LoadingData").dialog('open');
}
});
$(document).ajaxStop(function () {
//Close the loading dialog once the requests have finished
$("#LoadingData").dialog('close');
//Find the user opened dialog
$('.cmdialog').each(function () {
if ($(this).dialog('isOpen')) {
$(this).trigger('click');//set focus to dialog
// have also replaced .trigger('click') with .focus() but to no avail
}
}).on('click', function() {
//if click is triggerd set the focus of the dialog.
if ($(this).prop('id') != 'LoadingData') {
$(this).focus();
}
});
});
I have also tried setting the focus to the first element within the dialog with $('#DialogName:first-child').focus() and $('#DialogName:first-child').trigger('click') but this is also not working.
Any ideas as to why the focus is not set? Or am I misunderstanding/incorrectly using .focus() and .trigger('event')?
Thanks :)
Try the below code for close the dialog when Escap key is pressed:
$(document).keyup(function(e) {
if (e.keyCode == 27) { $("#LoadingData").dialog('close'); } // esc
});
I had the same issue, and found pretty elegant solution, in case you want to close dialog before actually clicking inside it:
$("#LoadingData").dialog({
...,
focus: function () {
$('#LoadingData').closest('.ui-dialog').focus();
}
});
So, we just need to set focus to parent .ui-dialog container, and in that case Esc will work for all cases. Disadvantage of $(document).keyup solution, if you have nested dialogs, Esc button will close your most top dialog and bottom one too.
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 (, , etc.) and links. docs here
You can try moveToTop method of the dialog, maybe it will help
And in your code, I think, you should bind "click" event before triggering it.
The following code should work even for multiple modals open:
$(document).on('keydown','.modal-dialog',function(event){
if (event.keyCode == 27) {
$(this).closest('.modal-dialog').find('[data-dismiss="modal"]').click();
}
});
This question already has an answer here:
How to stop alert box press enter loop?
(1 answer)
Closed 9 years ago.
When the user presses the Enter key anywhere on the body, it triggers the click event on another element which in turn opens a basic alert popup (for testing purposes).
This creates a loop because pressing Enter again will close the alert but will trigger the event again, opening a new alert, and the cycle repeats.
I'm using this in a modal box script. When the modal box appears, the user can press Enter to perform the action that a button inside the modal box would do, such as closing it (or in my case, opening an alert popup).
The click code:
//Add click events...
button.bind('click', mybtn, function(e) {
var click;
if (e.data.onclick) {
e.data.onclick(e);
} else if (e.data.click) {
e.data.click(e);
}
});
The key code:
//Add key events...
$('body').keyup(mybtn, function(e) {
var keyCode = e.keyCode || e.which;
//What key we need to match...
switch (e.data.key) {
case 'enter':
if (keyCode == 13) e.data.button.trigger('click');
break;
case 'esc':
case 'escape':
if (keyCode == 27) e.data.button.trigger('click');
break;
}
});
Should I bind my events in a different place (element)? Is there a better way to bind to stop this loop?
I can't unbind the key event because my script needs to be flexible enough to handle multiple key presses.
Example of creating a modal box:
createModal('HTML <b>content</b>', [{ label: 'Close', onclick: function() { alert('Modal closed'); }, key: 'enter' }]);
The HTML content is dumped into the modal, then the function will loop through the controls you've defined and will try to build them for you. In this example you define a "close" control, which would look like this (if you used onclick=""):
<button onclick="function() { alert('Modal closed'); }">Close</button>
with an event assigned to the document that when you press Enter it will trigger clicking that button, causing the problem.
button.one('click', mybtn, function(e) {
var click;
if (e.data.onclick) {
e.data.onclick(e);
} else if (e.data.click) {
e.data.click(e);
}
});
Will limit the click event to only one occurrence and then it unbinds itself.
There are two elements in play:
$('#myInput') // an input field for search
$('#myList') // a list to display search results
I want to hide the list when the input no longer has focus, like so:
$('#myInput').blur(function() {
$('#myList').hide();
});
This works great, except when a list item is clicked, because the blur event fires and hides the list before the click is registered. The goal is for the list to stay visible when any part of the list is clicked, even though this will cause the input to blur.
How can I do this? Thanks!
You can accomplish this by keeping a global variable, and setTimouts, to wait a delay of 200ms and then check if one of the 2 elements have focus.
var keepFocus = false;
function hideList(){
if(!keepFocus){
$('#myList').hide();
}
}
$('#myInput').blur(function() {
keepFocus = false;
window.setTimeout(hideList, 200);
}).focus(function(){
keepFocus = true;
});
$('#myList').blur(function() {
keepFocus = false;
window.setTimeout(hideList, 200);
}).focus(function(){
keepFocus = true;
});
I've faced with the exact same problem, so this is how I solved it.
I came up with the fact that blur() fires earlier than click().
So I've tried to change click() to mousedown() and found out that mousedown() fires before blur().
And to imitate click() you'll have to fire mousedown() and then mouseup()
So in your case I would do something like this:
var click_in_process = false; // global
$('#myList').mousedown(function() {
click_in_process = true;
});
$('#myList').mouseup(function() {
click_in_process = false;
$('#myInput').focus();
// a code of $('#myList') clicking event
});
$('#myInput').blur(function() {
if(!click_in_process) {
$('#myList').hide();
// a code of what you want to happen after you really left $('#myInput')
}
});
Demo / example: http://jsfiddle.net/bbrh4/
Hope it helps!
You need to be able to say "do this blur() unless the list gains focus at the same time".
This question says how to detect if an element has focus: Using jQuery to test if an input has focus
Then all you need to do is:
$("#myInput").blur(function () {
if (!$("#myList").is(":focus")) {
$("#myList").hide();
}
});
Pigalev Pavel's answer above works great.
However, If you want an even simplier solution, you can just "prevent default" in the "mousedown" of an element to prevent the blur event from taking place. (since preventing default actually means that in the end, the input never looses focus in the first place!)
Of course, this is only if you're alright with preventing default in the div. It does have some side-effects, like the text is no longer selectable. As long as that's not an issue, this will work.
I suppose if you hold the mouse down over the div, move the mouse outside of the div, and then release the mouse, it also doesn't fire the "blur" event. But in my case, I wasn't too worried about that either, since the click started in the target div.
$("input").focus(function(){
$(this).val("");
});
$("input").blur(function(){
$(this).val("blur event fired!");
});
$("div").mousedown(function(e){
e.preventDefault();
})
div{
height: 200px;
width: 200px;
background: blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input>
<div>
Click here to prevent blur event!
</div>
The best way to do this is to attach an event handler to the body element, then another handler to the list that stops event propagation:
$(body).click(function () {
$("#myList").hide();
});
$("#myList").click(function (e) {
e.stopImmediatePropagation();
});
This listens for a click outside of #myInput and hides #myList. At the same time, the second function listens for a click on #myList and if it occurs, it prevents the hide() from firing.
<script>
$("#test_img").click(function() {
alert("Hello");
});
</script>
But it doesn't matter what mouse button I'm pressing - right or left. I see absolutely the same result. I want alert to be shown only on left mouse button click.
Thank you and sorry; I'm little new to javascript.
Thank you.
You can evaluate the event.which attribute to determine which button has been pressed.
$("#test_img").mouseup(function(e) {
// e.which is 1, 2 or 3 for left / middle / right mouse button
if (e.which === 1) {
//continue
}
});
Furthermore, to safely detect a mousebutton, you cannot use the click-event! Use mousedown or mouseup instead.
Try it out here!