Haven't post in quite a while.
Anyway I was searching about my subject and I got this.
$(window).keyup(function(e) {
if (e.which === 8) {
$('.ilol'). fadeOut();
}
});
It's working perfectly fine. But when I change the window to a class or id it doesn't respond anymore.
There's not a lot of detail about the type of element you are trying to attach this event handler to, but the jQuery documentation explains that form elements (e.g. input) are a safe bet because they are able to be focused across most browsers:
The keyup event is sent to an element when the user releases a key on
the keyboard. It can be attached to any element, but the event is only
sent to the element that has the focus. Focusable elements can vary
between browsers, but form elements can always get focus so are
reasonable candidates for this event type.
http://api.jquery.com/keyup/
It may also be a selector issue. Make sure that your selector is working properly by pasting it in your browser's JavaScript console and see if it returns any elements.
Make sure you are binding event in ready function.
$(document).ready(function(){
$('.someClassName').keypress(function(e) {
if (e.keyCode === 8) {
$('.ilol'). fadeOut();
}
});
});
After some testing this is what worked best for me. The 40 key in this example is the down arrow key.
$(document).keydown(function(e)
{
if(e.keyCode == 40){
$('.ilol').fadeOut('fast');
}
});
Related
I am trying to stop the enter key from triggering all actions from other scripts on input fields.
Here is the code I am using:
$(document).bind("keydown", function(e) {
var code = e.keyCode || e.which;
if (code == 13) {
// alert('enter pressed');
e.preventDefault();
return false;
}
});
An example of the code in action is here http://jsfiddle.net/8SJYn/ ,
It should be disabling enter but it is not.
Opinions?
You can do it by turning off the keydown and blur events for the input created by the tagit for this element alone.
Try this:
$('#myTags + ul .ui-autocomplete-input').off('keydown').off('blur');
http://jsfiddle.net/JzJRY/
Go into tag-it.js, and on line 245, find this part and remove it:
event.which === $.ui.keyCode.ENTER
JavaScript events have a "bubbling" phase, where they fire first on the inner-most DOM element, and then work their way up to the top-level document. If you try to stop the event at the document level, as in your example code, it is too late.
In some browsers (Firefox, for one) there is a "capturing" phase that occurs before the bubbling phase, and it works in the opposite direction: from top down. You cannot add a capturing phase event handler using jQuery. You must use the native addEventListener function and pass true as the third parameter. If you add the code below into your jsfiddle, it will prevent the Enter keydown event in some browsers.
document.addEventListener('keydown', function (e) {
if (e.keyCode === 13) {
// alert('Enter keydown');
e.stopPropagation();
}
}, true);
Be aware that the tag-it control in your jsfiddle also performs its text-to-tag conversions on blur, so if you uncomment the alert statement above, it will perform its text-to-tag conversion anyway, because of the blur event that occurs when the alert message is displayed.
Lastly, if you want to prevent not just other scripts from processing the Enter keydown, but also the browser itself, add an e.preventDefault(); line to the above.
I have a <div> box displaying search message and some radio button for recent message. There is link option for slide toggle.
When you click on that link it will show some input field and check box and radio button. And at the same time the text of link change to hide option. If you click on that it will hide all the input and checkbox option.
When I refreash the whole page its working properly but when that paticular box or part is refreashing then the box is hiding and imediately hides. If you refresh that portion n number of times the box is going on toggling continously. I think the problem is in registration of event handler. So please give me some solution.
CODE :
$(document).ready(function() {
$(".SideBar-blockheader1").click(function() {
e.preventDefault();
$(".SideBar-blockcontent1").slideToggle("fast");
});
$(".SideBar-optionheader").click(function() {
$(".SideBar-optioncontent").slideToggle("fast");
$(this).text($(this).text() == $("#hideopt").attr('value') ? $("#showopt").attr('value') : $("#hideopt").attr('value'));
});
$(".SideBar-optionheader").text($("#showopt").attr('value'));
$(".SideBar-optioncontent").hide();
});
jQuery has a method, called data() which can be used to extract the attached handler information of an HTML element. You can see if the element has already a click handler, and if it has, then stop re-attaching another handler to it.
if(typeof $('#id').data('events').click == 'object')
{
// A click handler is already attached
}
else
{
// No click handler; Attach one;
}
Although you haven't provided code, I suspect you are using .click(). For jQuery 1.7+ you should be using .on() in delegate mode (the element you bind to is an ancestor, not the clickable element itself) or .delegate() if pre jQ 1.7.
For example:
$('someAncestor').on('click', 'a.specialLink', function(event) {
event.preventDefault();
// the rest of your code for the click handler
})
"someAncestor" is any valid selector that is an ancestor of your link that will not be destroyed, rebuilt, or otherwise manipulated after the DOM is built. It doesn't have to be the direct ancestor.
[updated below after seeing code sample and comments]
There are a few things going on. First, .on() will only work if you're using jQuery 1.7+. Next, .on() can be invoked a few different ways (I wrote about it here: http://gregpettit.ca/2011/jquery-events-its-on/) and you need to be invoking it while delegating an ancestor listener, not simply as a substitute for click. Next, you haven't provided code for your attempted update, only for the original code; it's hard to tell what "didn't work" about trying to use .on(). Moving along, I'm not actually sure what this line is meant to do:
$(this).text($(this).text() == $("#hideopt")...etc...
I can't think of why you would want to try to treat a jQuery object as a variable. I'm not saying the code is wrong, I'm just saying I don't get it. Also, I hate ternary operators... which is part of the reason I don't get it. I much prefer readable conditionals. ;-)
Next, you're calling preventDefault() on "e" but you're not passing "e" into your functions. You might just be getting a JavaScript error, period. (e is undefined)
Then there's attr("value") which I believe should actually work. But why not use .val() if it is indeed a node that HAS a value attribute?
Finally, there is tonnes of room for caching your objects. Every time you see that an object is being used more than once, you can benefit (to varying degrees of performance and legibility) from caching it. I have not updated the code with any caching, though-- that's really something for a whole other "How can I best cache my objects?" question.
Anyhow... to solve the problem, you first have to choose a valid ancestor. This can be any ancestor that isn't destroyed during the process of loading in your new data. This could be anything, but the closest ancestor is the best. It might be a section wrapper, but if you're truly desperate it could be a page wrapper or even the body tag. If you bind to document, you're reproducing the deprecated .live() function, which I definitely recommend against. I have used a placeholder selector, ".section" but you need to figure out what an appropriate ancestor is on your page.
$(document).ready(function()
{
$(".section").on("click", ".SideBar-blockheader1", function(e)
{
e.preventDefault(); // probably not necessary if there's no default click behaviour
$(".SideBar-blockcontent1").slideToggle("fast");
});
$(".section").on("click", ".SideBar-optionheader", function(e)
{
e.preventDefault(); // probably not necessary if there's no default click behaviour
$(".SideBar-optioncontent").slideToggle("fast");
$(this).text($(this).text() == $("#hideopt").val() ?$("#showopt").val() : $("#hideopt").val());
});
$(".SideBar-optionheader").text($("#showopt").val());
$(".SideBar-optioncontent").hide();
});
I have an input field that I would like to validate on when the user either presses enter or clicks away from it, for this I use the events keypress and blur. If the input fails validation, an alert box is called.
I noticed that in IE (all versions), if I press enter with invalid input, for some reason both the keypress and blur events are fired (I suspect it's the alert box, but it doesn't do this on FF/Chrome) and it shows two of the same alert box. How can I have it so only one is shown?
EDIT: In FF/Chrome, I now noticed that a second alert box appears when I click anywhere after I try to validate with enter.
Simplified code:
$("#input-field").keypress(function(event) {
if (event.keycode == 13) {
event.stopPropagation();
validate();
return false;
}
});
$("#input-field").blur(function() {
validate();
});
function validate() {
if ($("#input-field").val() == '') {
alert("Invalid input");
}
}
EDIT: Ah-ha. Not really a fix but a separate detail I forgot - I need to restore the invalid input to its previously valid value, so when the validate function checks the value again it doesn't fail twice.
I ended up just checking for an IE UserAgent and skipping the keypress event for IE (binding keypress and blur to the same function, as below). Not a direct or terrific solution, tragically, but I've been looking to solve the same problem to no avail. Some minor notes that might be helpful: jQuery normalizes which, so you can confidently use e.which == 13 with keypress. I'd also combine the functions into one bind, e.g.
$("#input-field").bind('blur keypress', function(e) {
if(e.which == 13) {
// keypress code (e.g. check for IE and return if so)
}
validate();
});
I've tried setting globals and using jQuery's data() to assign arbitrary flags to indicate whether (in your case) validation has already been triggered for the element, but the events trigger simultaneously or at least, if sequentially, rapidly enough that even with an opening line setting some flag to true did not do the trick. I'd read that putting in a tiny callback delay might help, but that is hella dirty and I wouldn't do it even as a workaround so I've not tested it. stopPropagation() and preventDefault() also did not help.
Firefox does not get the keypress event right. Those events are only triggered when a key combination that produces a character is pressed (which is not the same as pressing any key).
Use keydown instead (as this is probably the only event IE handles correctly - as it should, since MS "invented" it ;-) ).
See http://www.quirksmode.org/dom/events/keys.html.
I have this right now:
$(document).click(function(e) { alert('clicked'); });
In Firefox, this event is firing when I left-click OR right-click. I only want it to fire when I left-click.
Does attaching a click handler to the document work differently than attaching it to other elements? For other elements, it only seems to fire on left clicks.
Is there a way to detect only left clicks besides looking at e.button, which is browser-dependent?
Thanks
Try
$(document).click(function(e) {
// Check for left button
if (e.button == 0) {
alert('clicked');
}
});
However, there seems to be some confusion as to whether IE returns 1 or 0 as left click, you may need to test this :)
Further reading here: jQuery Gotcha
EDIT: missed the bit where you asked not to use e.button. Sorry!
However, the example here returns the same ID regardless of looking at it in FF or IE, and uses e.button. could possibly have updated the jQuery framework? The other answer is that older versions of IE return a different value, which would be a pain. Unfortunately I only have IE 7/8 here to test against.
You could simply register for a "contextmenu" event like this:
$(document).bind("contextmenu",function(e){
return false;
});
Taken from: http://www.catswhocode.com/blog/8-awesome-jquery-tips-and-tricks
I've read that if you bind with "live" in jQuery 1.3, jQuery normalizes the click between browsers. I've not tested this.
However, this would indicate that it doesn't: http://abeautifulsite.net/notebook/99
Since you say click works correctly everywhere but on "document," have you tried a 100% div over the document to catch the click?
There is no not-browser-dependent way to detect only left-clicks. You can use this code that works under IE and non-IE browsers:
$("#element").live('click', function(e) {
if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
// Left mouse button was clicked (all browsers)
}
});
Taken from: http://abeautifulsite.net/notebook/99
Does anyone know of crossbrowser equivalent of explicitOriginalTarget event parameter? This parameter is Mozilla specific and it gives me the element that caused the blur. Let's say i have a text input and a link on my page. Text input has the focus. If I click on the link, text input's blur event gives me the link element in Firefox via explicitOriginalTarget parameter.
I am extending Autocompleter.Base's onBlur method to not hide the search results when search field loses focus to given elements. By default, onBlur method hides if search-field loses focus to any element.
Autocompleter.Base.prototype.onBlur = Autocompleter.Base.prototype.onBlur.wrap(
function(origfunc, ev) {
var newTargetElement = (ev.explicitOriginalTarget.nodeType == 3 ? ev.explicitOriginalTarget.parentNode: ev.explicitOriginalTarget); // FIX: This works only in firefox because of event's explicitOriginalTarget property
var callOriginalFunction = true;
for (i = 0; i < obj.options.validEventElements.length; i++) {
if ($(obj.options.validEventElements[i])) {
if (newTargetElement.descendantOf($(obj.options.validEventElements[i])) == true || newTargetElement == $(obj.options.validEventElements[i])) {
callOriginalFunction = false;
break;
}
}
}
if (callOriginalFunction) {
return origFunc(ev);
}
}
);
new Ajax.Autocompleter("search-field", "search-results", 'getresults.php', { validEventElements: ['search-field','result-count'] });
Thanks.
There is no equivalent to explicitOriginalTarget in any of the other than Gecko-based browsers. In Gecko this is an internal property and it is not supposed to be used by an application developer (maybe by XBL binding writers).
2015 update... you can use event.relatedTarget on Chrome. Such a basic thing, hopefully the other browsers will follow...
The rough equivalent for Mozilla's .explicitOriginalTarget in IE is document.activeElement. I say rough equivalent because it will sometimes return a slightly different level in the DOM node tree depending on your circumstance, but it's still a useful tool. Unfortunately I'm still looking for a Google Chrome equivalent.
IE srcElement does not contain the same element as FF explicitOriginalTarget. It's easy to see this: if you have a button field with onClick action and a text field with onChange action, change the text field and move the cursor directly to the button and click it. At that point the IE srcElement will be the text field, but the explicitOriginalTarget will be the button field. For IE, you can get the x,y coordinates of the mouse click from the event.x and event.y properties.
Unfortunately, the Chrome browser provides neither the explicitOriginalTarget nor the mouse coordinates for the click. You are left to your own devices to figure out where the onChange event was fired from. To do this, judicious use of mousemove and mouseout events can provide mouse tracking which can then be inspected in the onChange handler.
Looks like it is more designed for extension writers than for Web design...
I would watch the blur/focus events on both targets (or potential targets) and share their information.
The exact implementation might depend on the purpose, actually.
For IE you can use srcElement, and forced it.
if( !selectTag.explicitOriginalTarget )
selectTag.explicitOriginalTarget = selectTag.srcElement;
In case of form submit events, you can use the submitter property in all modern browser (as of 2022).
let form = document.querySelector("form");
form.addEventListener("submit", (event) => {
let submitter = event.submitter; //either a form input or a submit button
});