hide element press Esc - javascript

This code doesn't hide the box div which was supposed to be hidden when I press the Esc key.
function Boxup(elementN, event){
$("#"+elementN).css({
"display":"block",
"top":event.pageY+"px" ,
"left":event.pageX+"px"
})
}
function hideCurrentPopup(ele){
$(ele).parent().hide();
}
$(this).keyup(function(event) {
if (event.which == 27) {
disablePopup();
}
});
Am I missing something?

From your code I cannot exactly tell what's this referring to in this line:
$(this).keyup(function(event) {
cause it this refers to a "textarea" or "input" it will trigger the event if that element has focus, otherwise you're looking for keyup events registered by document
but here's what you can try.
function Boxup(elementN, event){
$("#"+elementN).css({
display : "block",
top : event.pageY , // px are not needed as they are default unit in jQ
left : event.pageX
})
}
function hideCurrentPopup(ele){ // note your function name and the argument!
$(ele).parent().hide(); // (do you need .parent()? I don't know
} // without seeing any HTML sample)
$(document).keyup(function(event) { // document is probably the selector you want
if (event.which == 27) {
hideCurrentPopup("#hereYourPopupID"); // try alike
}
});
P.S: Make sure that by using $(some Selector here).keyup(function(event) { you're not preventing in any case a keyup event to bubble up the DOM tree to reach the documentElement

Related

Click is being invoked before focusOut event in js

I have input element which will take input and filter the contents and the filter event will be trigger once the user gets focused out from the input element.
When the user having the focus in the input element and he clicks in one of the button, the click event is invoked first and then the focus out event, as it creates conflicts while generating the filtered content.
I tried changing the order of code and other options such as changing the way of invocation of the click event - none of the ways worked out for me
$('body').on('focusout', '.classname', functionname);
function functionname(e) {
if (typeof e == 'object') {
}
}
$('body').on('click', '.buttonclass', function (e) {});
Could someone help me to build The FocusOut event to trigger first and then the click event.
Based on the current conditions, you have to - inside the click handler - retrieve the validation result, and based on that result, decide if button submission should or should not occur.
JS Code:
$("#input").focusout(function(){
var that = this;
valid = this.value.length ? true : false;
!valid && window.setTimeout(function() {
$(that).focus();
}, 0);
});
$("#button").click(function(e) {
if ( !valid ) { return false; }
e.preventDefault();
alert('execute your filter)');
});

How to detect if mouse cursor is out of element?

I have a listener which runs when I click on document.
document.addEventListener('click', print);
function print(element)
{
doSomething();
}
It creates div id=panel, where I print some information.
When I run the print function I would like to detect whether I clicked outside of the div#panel (The panel exists when I click second time).
I wish not to use the mouseout event listener because I think it is redundant to use listener for mouse movements when the event click is already fired.
How to detect when I clicked out of div#panel?
You can check the target of jQuery's click event, which element it was:
$(document).click(function(e) {
var target = $(e.target);
if( !target.is("#panel") && target.closest("#panel").length === 0 ) {
// click was not on or inside #panel
}
});
Your event handler gets passed an event object, not an element. Since you are listening for the click event, the event will be of type MouseEvent and that event object will have a target property which you can use to check if the target element matches your desired element.
function handler(event) {
if (event.target == document.getElementById("panel")) {
// Do stuff
}
}
document.addEventListener('click', handler);
Edit: I intentionally gave the vanilla JS answer since your own code fragments don't use jQuery. But jQuery wouldn't change anything as its event handling API is almost just a thin wrapper over JS.
I am just using event from the click. Here it is
var elem=document.getElementById("elem");
var rects=elem.getBoundingClientRect();//get the bounds of the element
document.addEventListener('click', print);
function print(e)
{
//check if click position is inside or outside target element
if(e.pageX<= rects.left +rects.width && e.pageX>= rects.left && e.pageY<= rects.top +rects.height && e.pageY>= rects.top){
console.log("Inside element");
}
else{
console.log("Outside element");
}
}
JS Bin link : https://jsbin.com/pepilehigo/edit?html,js,console,output
A different approach, using only javascript is:
function print(evt) {
if (!(evt.target.tagName == 'DIV' && evt.target.classList.contains('myDiv'))) {
var div = document.createElement('div');
div.classList.add('myDiv');
div.textContent="new div";
document.body.appendChild(div);
}
}
window.onload = function() {
document.addEventListener('click', print);
}
.myDiv {
border:1px solid green;
}

jQuery event listener basic understanding

I wanted to get a fuller understanding of how Javascript handles events. click() triggers a div to pop up, but once that div is closed it doesn't respond to the event again.
What is a good way to keep this event loop going?
$project.click(function() {
$popup = $(".popup");
$np.hide();
$popup.append($html);
// EXIT THE POPUP
$(document).bind('keydown',function(e) {
if (e.which == 27) {
$popup.hide();
$np.show("slow");
}
});
$(".exitbutton").click(function() {
$popup.hide();
$np.show("slow");
});
});
If .popup element is set to display:none at page load, can try using .toggle() at $project click handler. Also defined $popup , moved keydown event to outside of click handler, where appears to be added as event handler at each click of $project
var $popup = $(".popup");
$project.click(function() {
$np.toggle();
$popup.append($html).toggle();
});
// EXIT THE POPUP
$(document).bind("keydown",function(e) {
if (e.which == 27) {
$popup.hide();
$np.show("slow");
}
});
$(".exitbutton").click(function() {
$popup.hide();
$np.show("slow");
});

How do we detect a double click outside an element?

I have this function:
this.div.click( function(e) {
...
});
I would like to listen for double clicks outside this element. I know that we can use blur() for clicks outside an element. But I would like to handle only double click events. What's the best way to do this?
You can use the .dblclick() event to listen to the double-click at the body level, and then use it's target attribute and .contains() to see if the click occurred within the div.
Something like this:
// div to check if dbl click did _not_ originate from
var mydiv = jQuery("#mydiv").get(0);
// listen to body for double clicks
$("body").dblclick(function(e) {
// if click target does not fall within #mydiv
if (mydiv !== e.target && $.contains(mydiv, e.target) !== true) {
console.log("outside of mydiv");
}
});
Here is a jsbin demo.
There is another way to do this, by modifying e.originalEvent:
$( "#mydiv" ).dblclick(function(e) {
e.originalEvent.inside = true;
});
$( "body" ).dblclick(function(e) {
if( e.originalEvent.inside ) {
console.log('inside');
} else {
console.log('outside');
};
});
I have updated Johnatan's Bin. Think it should be faster.

Keyup event behavior on tab

In this demo, if you place your cursor in the first field and then tab out (without making any changes), the keyup event is fired on the second field. i.e., you are tabbing out of first field and into second field. Is this behavior correct? How can I prevent this from happening? Same applies to shift + tab.
Note:
a) I believe all other keys, printable and non-printable, trigger the keyup event on the first field.
b) The event isn't triggered at all if you keep the tab pressed until it moves out of both fields.
HTML:
<form id="myform">
<input id="firstfield" name="firstfield" value="100" type="text" />
<input id="secondfield" name="secondfield" value="200" type="text" />
</form>
jQuery:
jQuery(document).ready(function() {
$('#firstfield').keyup(function() {
alert('Handler for firstfield .keyup() called.');
});
$('#secondfield').keyup(function() {
alert('Handler for secondfield .keyup() called.');
});
});
A key's default action is performed during the keydown event, so, naturally, by the time keyup propagates, the Tab key has changed the focus to the next field.
You can use:
jQuery(document).ready(function() {
$('#firstfield, #secondfield').on({
"keydown": function(e) {
if (e.which == 9) {
alert("TAB key for " + $(this).attr("id") + " .keydown() called.");
}
},
"keyup": function(e) {
if (e.which != 9) {
alert("Handler for " + $(this).attr("id") + " .keyup() called.");
}
}
});
});
This way, if the Tab key is pressed, you can make any necessary adjustments before handling other keys. See your updated fiddle for an exampe.
Edit
Based on your comment, I revamped the function. The JavaScript ended up being a bit complicated, but I'll do my best to explain. Follow along with the new demo here.
jQuery(document).ready(function() {
(function($) {
$.fn.keyAction = function(theKey) {
return this.each(function() {
if ($(this).hasClass("captureKeys")) {
alert("Handler for " + $(this).attr("id") + " .keyup() called with key "+ theKey + ".");
// KeyCode dependent statements go here.
}
});
};
})(jQuery);
$(".captureKeys").on("keydown", function(e) {
$("*").removeClass("focus");
$(this).addClass("focus");
});
$("body").on("keyup", "*:focus", function(e) {
if (e.which == 9) {
$(".focus.captureKeys").keyAction(e.which);
$("*").removeClass("focus");
}
else {
$(this).keyAction(e.which);
}
});
});
Basically, you give class="captureKeys" to any elements on which you want to monitor keypresses. Look at that second function first: When keydown is fired on one of your captureKeys elements, it's given a dummy class called focus. This is just to keep track of the most recent element to have the focus (I've given .focus a background in the demo as a visual aid). So, no matter what key is pressed, the current element it's pressed over is given the .focus class, as long as it also has .captureKeys.
Next, when keyup is fired anywhere (not just on .captureKeys elements), the function checks to see if it was a tab. If it was, then the focus has already moved on, and the custom .keyAction() function is called on whichever element was the last one to have focus (.focus). If it wasn't a tab, then .keyAction() is called on the current element (but, again, only if it has .captureKeys).
This should achieve the effect you want. You can use the variable theKey in the keyAction() function to keep track of which key was pressed, and act accordingly.
One main caveat to this: if a .captureKeys element is the last element in the DOM, pressing Tab will remove the focus from the document in most browsers, and the keyup event will never fire. This is why I added the dummy link at the bottom of the demo.
This provides a basic framework, so it's up to you to modify it to suit your needs. Hope it helps.
It is expected behavior. If we look at the series of events happening:
Press Tab Key while focus is on first text box
Trigger key down event on first text box
Move focus to second text box
Lift finger off tab key
Keyup event is triggered on second text box
Key up is fired for the second text box because that is where it occurs since the focus was shifted to that input.
You can't prevent this sequence of events from happening, but you could inspect the event to see what key was pressed, and call preventDefault() if it was the tab key.
I was recently dealing with this for a placeholder polyfill. I found that if you want to capture the keyup event in the originating field, you can listen to the keydown event and fire the keyup event if a tab was pressed.
Instead of this:
$(this).on({'keyup': function() {
//run code here
}
});
Change to this:
$(this).on({'keydown': function(e) {
// if tab key pressed - run keyup now
if (e.keyCode == 9) {
$(this).keyup();
e.preventDefault;
}
},
'keyup': function() {
//run code here
}
});
I ended up using this solution:
HTML:
<form id="myform">
<input id="firstfield" name="firstfield" value="100" type="text" />
<input id="secondfield" name="secondfield" value="200" type="text" />
</form>
jQuery:
jQuery(document).ready(function () {
$('#firstfield').keyup(function (e) {
var charCode = e.which || e.keyCode; // for cross-browser compatibility
if (!((charCode === 9) || (charCode === 16)))
alert('Handler for firstfield .keyup() called.');
});
$('#secondfield').keyup(function (e) {
var charCode = e.which || e.keyCode; // for cross-browser compatibility
if (!((charCode === 9) || (charCode === 16)))
alert('Handler for secondfield .keyup() called.');
});
});
This solution doesn't run the alert if the key is tab, shift or both.
Solution: http://jsfiddle.net/KtSja/13/

Categories