Issues catching the 'Page Down'/'Page Up' key events - javascript

I need to catch when the PageUp/PageDown keys are pressed and an element is scrolled, but I've so far been unable to do so. I've tried
Listening for 'keydown' event**: an event triggers when a non-scrolling element is in focus, but when a scrolling element is in focus, no event fires
$(window).on('keydown', function(e)
{
console.log(e.keyCode === 34);
});
Listening for 'keypress' event**: no event triggers in any context
$(window).on('keypress', function(e)
{
console.log("keypress"); //does nothing
});
Listening for 'scroll' event**: no event triggers in any context
$(window).scroll(function()
{
console.log("scrolling"); //does nothing
});
I'm at a loss and I haven't been able to find any clues.
I've tried my current code in a jsFiddle, and it works fine, so it must be something more specific.

instead of window try to use document so it will consider current document on web page.
in your code there is bracket miss match.
$(document).ready(function(){
$(document).keypress(function(e){
if(e.keyCode === 34){
console.log('page down')
}
});
$(document).keypress(function(e){
console.log("keypress"); //console will print
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
hope this will work for you.

Can you try also ?
$(window).bind('keydown', function(event) {
console.log(event.which === 33) });
The event.which property returns which keyboard key or mouse button was pressed for the event

Actually your syntax is incorrect you are missing a closing ) at the end of your function, you should write:
$(window).on('keydown', function(e) {
console.log(e.keyCode === 34);
});
$(window).on('keypress', function(e) {
console.log("keypress"); //does nothing
});
$(window).scroll(function() {
console.log("scrolling"); //does nothing
});
#scroll {
max-height: 100px;
height: 100px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="scroll">
<br>fghfjkjgfj
<br/>dfdfdfdf
<br/>dfdsf
<br/>
<br/>
<br/>dfdfdf
<br/>
<br/>
<br/>ssdsds
<br/>fdf
<br/>
<br/>
<br/>
<br/>fgfgfg
<br/>End
</div>
And everything, will work as expected.

So the element I'm trying to scroll on is a SlickGrid table, and it has its own scrolling event.
So I wrote, based on their docs:
this.grid.onScroll.subscribe(function(e, args)
{
console.log(e);
}
Now it is triggering on Page Down / Page Up key-presses.

Related

How to check if the focus event is triggered programmatically

I want to know if the focus event is triggered programtically or by human ?
I am writing the part of the script
jQuery( document ).on( 'focus', '#song_artist_focus', function(event) {
if(event.originalEvent === undefined ){
alert('I am not human');
return;}
alert('I am human') ;
});
And when i call this script programtically like this
jQuery('#song_artist_focus').focus();
It still shows that event is triggred by human. Please help ?
UPDATE
I checked this solution Check if event is triggered by a human. But doesn't work on focus events.
Your problem is that the focus event doesn't bubble.
jQuery fixes that with a little magic to make it more like the other events, but it still doesn't quite work like an event that naturally bubbles.
To fix the problem, use the focusin event instead, as it bubbles, and do .trigger('focusin')
jQuery(document).on('focusin', '#song_artist_focus', function(event) {
if (event.originalEvent === undefined) {
console.log('I am not human');
} else {
console.log('I am human');
}
});
jQuery('#song_artist_focus').trigger('focusin');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="song_artist_focus">
Html :
<input type='text' id='try' >try
<button id='click'>Click</button>
jQuery :
$("#try").focus(function(event) {
if (event.originalEvent === undefined) {
console.log('not human')
} else {
console.log(' human');
}
});
$('#click').click(function(event) {
jQuery('#try').focus();
});
Try it , you will get expected result.

jQuery UI Dialog Button Won't Click

The alert is working, but the button just won't click...
$('#loginDialog .field input').keyup(function (e) {
if (e.keyCode == 13) {
alert('it is working!');
$('.ui-button').click();
return false;
}
});
I have tried many different things, including reinitializing the method when the dialog gets opened, but nothing seems to work...
Html:
<div id="loginDialog" title="Please Login">
<div class="label">Password:</div>
<div class="field"><input type="password" /></div>
</div>
the ui-button is generated by jquery ui
I'm assuming from your comment that the button is generated dynamically and that any click event you have bound to is will have to be bound using event delegation, similar to:
$('body').on('click', '.ui-button', function(){...)
Instead of body, using the closest static element will work as well and would be preferred.
Please, try this:
$(function() {
$('#loginDialog .field input').keyup(function (e) {
if (e.keyCode == 13) {
alert('it is working!');
$('.ui-button').trigger('click');
return false;
}
});
$('.ui-button').click(function() {
alert('hello world');
});
};
Here there is an example: http://jsfiddle.net/netme/YZH3B/
This should trigger the event ...
$('.ui-button').trigger('click');

Click on parent, ignore its children [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery: click function exclude children.
I have two divs, something like this:
<div id="parent" style="width: 100%; height: 100%; background-color:red;" />
<h1>I'm the parent!</h1>
<div id="child" style="width: 300px; height: 200px; background-color:yellow;">
</h2>..and I'm the child!</h2>
</div>
</div>
Additionally, I have the following JavaScript code:
$(document).ready(function(){
$('#parent').click(function(){
alert('Parent was clicked');
});
});
The problem is, if I click on the child, the event is triggered. How can I limit this event to the parent only?
Edit: Just to clarify; I want this action to trigger when the user clicks anywhere in the red. As said in the comments; the h1 is not the parent. Tjirp's answer did the trick, and there's a lots of working variants of this solution in the answers.
This should work
$(document).ready(function() {
$('#parent').click(function(e) {
if (e.target == this) {
alert('Parent was clicked');
}
}
}
This way you won't have to bind anything to your childs. The click event is propagated to your click handler, and it checks if the target of the click event is indeed the element you added the event on.
Edit: I was right. this is not the most efficient way, Alessandro Minoccheri answer should be way faster. I updated my code with his.
Try this:
$('#parent').click(function(data, handler){
if (data.target == this) {
//Do Stuff (only element clicked, not children)
}
});
h1 is not the parent, div#parent is the parent.
clicking div#child triggers click on div#parent because of event bubbling.
this will prevent event bubbling:
$('#child').on("click", function() {
return false;
});
The easiest solution is to check that the element that originated the event (event.target) is the same as the element handling the click event handler (this):
$('#parent').click(function(event){
if(this === event.target) {
alert('Parent was clicked');
}
});
Here's a working jsFiddle.
You can try something like:
$(document).ready(function(){
$('#parent h1').click(function(){
alert('Parent was clicked');
});
});
$(document).ready(function(){
$('#parent').click(function(){
if($(this).not("#parent")) {
return false;
} else {
alert('Parent was clicked');
};
});
});

jquery selector help. Everything but the specified selector

I have the following function to open an overlay menu:
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
});
To hide the menu, I would like the user to be able to click on any area outside ".context-switch-menu"
I am trying with :not() but with no success..
$('body').click(function(e) {
if ($(e.target).hasClass('context-switch')) {
return;
}
$(".context-switch-menu").hide();
});
$('.context-switch').click(function() {
$(".context-switch-menu").toggle();
return false;
});
The reason this can be difficult is because of event bubbling.
You can try something like this:
$('.context-switch').click(function(e) {
e.stopPropagation();
$(".context-switch-menu").toggle();
});
$(".context-switch-menu").click(function(e){
e.stopPropagation();
});
$("body").click(function(e){
$(".context-switch-menu").hide();
});
The e.stopPropagation() prevents the click event from bubbling to the body handlers. Without it, any click to .context-switch or .context-switch-menu would also trigger the body event handler, which you don't want, as it would nullify the effect of the .context-switch click half the time. (ie, if the state is hidden, and then you click to show, the event would bubble and trigger the body handler that would then hide the .context-switch-menu again.)
Without testing, would something like this work?:
$('.context-switch').click(function() {
$(".context-switch-menu").show();
});
$(document).click(function() {
$(".context-switch-menu").hide();
});
Instead of using document, 'html' or 'body' may work as well.
$(document).on('click', function(e) {
if (e.target.className !='context-switch-menu') {
$(".context-switch-menu").hide();
}
});
Just an idea here, based on what what others have suggested in the past:
$(document).click(function(e){
//this should give you the clicked element's id attribute
var elem = $(e.target).attr('classname');
if(elem !== 'context-switch-menu'){
$('.context-switch-menu').slideUp('slow');
//or however you want to hide it
}
});
try this, we don't want to call a function when you clicked on the element itself, and not when we click inside the element. That's why we need 2 checks.
You want to use e.target which is the element you clicked.
$("html").click(function(e){
if( !$(e.target).is(".context-switch-menu") &&
$(e.target).closest(".context-switch-menu").length == 0
)
{
alert("CLICKED OUTSIDE");
}
});
Live fiddle: http://jsfiddle.net/Xc25K/1/

JQuery Event for user pressing enter in a textbox?

Is there any event in Jquery that's triggered only if the user hits the enter button in a textbox? Or any plugin that can be added to include this? If not, how would I write a quick plugin that would do this?
You can wire up your own custom event
$('textarea').bind("enterKey",function(e){
//do stuff here
});
$('textarea').keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterKey");
}
});
http://jsfiddle.net/x7HVQ/
$('#textbox').on('keypress', function (e) {
if(e.which === 13){
//Disable textbox to prevent multiple submit
$(this).attr("disabled", "disabled");
//Do Stuff, submit, etc..
//Enable the textbox again if needed.
$(this).removeAttr("disabled");
}
});
Here is a plugin for you: (Fiddle: http://jsfiddle.net/maniator/CjrJ7/)
$.fn.pressEnter = function(fn) {
return this.each(function() {
$(this).bind('enterPress', fn);
$(this).keyup(function(e){
if(e.keyCode == 13)
{
$(this).trigger("enterPress");
}
})
});
};
//use it:
$('textarea').pressEnter(function(){alert('here')})
heres a jquery plugin to do that
(function($) {
$.fn.onEnter = function(func) {
this.bind('keypress', function(e) {
if (e.keyCode == 13) func.apply(this, [e]);
});
return this;
};
})(jQuery);
to use it, include the code and set it up like this:
$( function () {
console.log($("input"));
$("input").onEnter( function() {
$(this).val("Enter key pressed");
});
});
jsfiddle of it here http://jsfiddle.net/VrwgP/30/
It should be well noted that the use of live() in jQuery has been deprecated since version 1.7 and has been removed in jQuery 1.9. Instead, the use of on() is recommended.
I would highly suggest the following methodology for binding, as it solves the following potential challenges:
By binding the event onto document.body and passing $selector as the second argument to on(), elements can be attached, detached, added or removed from the DOM without needing to deal with re-binding or double-binding events. This is because the event is attached to document.body rather than $selector directly, which means $selector can be added, removed and added again and will never load the event bound to it.
By calling off() before on(), this script can live either within within the main body of the page, or within the body of an AJAX call, without having to worry about accidentally double-binding events.
By wrapping the script within $(function() {...}), this script can again be loaded by either the main body of the page, or within the body of an AJAX call. $(document).ready() does not get fired for AJAX requests, while $(function() {...}) does.
Here is an example:
<!DOCTYPE html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
var $selector = $('textarea');
// Prevent double-binding
// (only a potential issue if script is loaded through AJAX)
$(document.body).off('keyup', $selector);
// Bind to keyup events on the $selector.
$(document.body).on('keyup', $selector, function(event) {
if(event.keyCode == 13) { // 13 = Enter Key
alert('enter key pressed.');
}
});
});
</script>
</head>
<body>
</body>
</html>
If your input is search, you also can use on 'search' event. Example
<input type="search" placeholder="Search" id="searchTextBox">
.
$("#searchPostTextBox").on('search', function () {
alert("search value: "+$(this).val());
});
//Short and simple solution
$(document).ready(function(){
$('#TextboxId').keydown(function(event){
if (event.which == 13){
//body or action to be performed
}
});
});
HTML Code:-
<input type="text" name="txt1" id="txt1" onkeypress="return AddKeyPress(event);" />
<input type="button" id="btnclick">
Java Script Code
function AddKeyPress(e) {
// look for window.event in case event isn't passed in
e = e || window.event;
if (e.keyCode == 13) {
document.getElementById('btnEmail').click();
return false;
}
return true;
}
Your Form do not have Default Submit Button
Another subtle variation.
I went for a slight separation of powers, so I have a plugin to enable catching the enter key, then I just bind to events normally:
(function($) { $.fn.catchEnter = function(sel) {
return this.each(function() {
$(this).on('keyup',sel,function(e){
if(e.keyCode == 13)
$(this).trigger("enterkey");
})
});
};
})(jQuery);
And then in use:
$('.input[type="text"]').catchEnter().on('enterkey',function(ev) { });
This variation allows you to use event delegation (to bind to elements you haven't created yet).
$('body').catchEnter('.onelineInput').on('enterkey',function(ev) { /*process input */ });
I could not get the keypress event to fire for the enter button, and scratched my head for some time, until I read the jQuery docs:
"The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events." (https://api.jquery.com/keypress/)
I had to use the keyup or keydown event to catch a press of the enter button.
<form name="searchForm" id="searchForm" onsubmit="doSomething(event)">
<input type="text" name="search" id="search">
</form>
<script>
function doSomething(event){
let $val = $('form#searchForm input[name="search"]').val();
console.log($val);
event.preventDefault();
}
</script>
One simple way it can be done in this way. Enter text or number, hit enter key and get the entered input value.

Categories