A quick question about keypress and jQuery - javascript

$(document).keydown(function(e) {
Well, that's my code - I was wondering if it is possible to have something like:
$(document).not('#pinkElephant').keydown(function(e) {
(Except, that doesn't work...)
Any Ideas?
Thanks very much!
p.s. All that function has inside it, is a switch statement.
[edit] Hey guys n gals - I cannot return false; because the element I need to type in is an <input> text, so the keyboard still needs to return here.
It's really confusing me :(

Here's an alternate way to do what you require by checking to see that the target element's id isn't pinkElephant. Since this doesn't use the universal selector '*' it should perform better:
$(document).keydown(function(e) {
if (e.target.id !== "pinkElephant") {
alert("I'm not pink!");
}
});
Here's a working example.
(updated from comment)

If you really want to bind a keydown event handler to all nodes in your markup, with the exception of #pinkElephant you need to do it like this:
$(document).find('*').not('#pinkElephant').keydown(function() ..
or short
$(':not(#pinkElephant').keydown(function() ...
which implicitly uses the universal selector *.
Note, that this is never ever any good in terms of performance. I don't know your markup but I hope it's not very crouded using that kind of selector.
update
inspired by a comment, you could also do it like:
$(document).click(function(event) {
if( event.target.id === 'pinkElephant' || $.contains($('#pinkElephant')[0], event.target) )
return false;
// ...
});
Last snippet checks whether #pinkElephant itself or a child node was clicked and prevents the propagation + the default action. This is done by invoking $.contains()help

I assume you don't want elements inside pinkElephant to trigger the keydown.
Place a handler on #pinkElephant that stops propagation of the event.
$('#pinkElephant').bind('keydown',false);
Note that passing false to .bind() requires jQuery 1.4.3 or later.
If you're using an older version, do this:
$('#pinkElephant').bind('keydown',function(){return false;});

Try this instead:
$(':not(#pinkElephant)').keydown(function(e) {
// ...
});

Related

is this javascript code correct?

I am trying to remove a class when clicking on an element with a specific class. I made this javascript and it does work. But is this correct syntax to do it this way Can this be more efficient?
// Clear notifications alerts
$(document).on('click', '.js-clear-notifications', function() {
$('.AlertNotifications').remove();
});
// clear inbox alerts
$(document).on('click', '.js-clear-inbox', function() {
$('.AlertInbox').remove();
});
Your javascript code is correct, provided that you load jQuery as well.
Furthermore you have the most efficient solution, where you use a single event handler to handle events that originate on multiple elements.
The alternative would be:
$('.js-clear-notifications').on('click', function() {
$('.AlertNotifications').remove();
});
Which attaches as many event handlers as there are elements in the jQuery object. Slightly less efficient, though probably you would never notice except in extreme cases.
To me a more proper way to do it is something like this:
...
$('.js-clear-inbox').on('click', function() {
$('.AlertInbox').remove();
});
...
I will also suggest to have more specific selectors i.e.
$('div .js-clear-inbox')
I hope that this helps.
I am editing this in response to the feedback in the comments.
If what you want is to remove all elements with AlertNotifications class, which is what your code does, then what you have is correct.
If what you want is to remove only the class, which is what the text of the post said, you want removeClass, not remove:
$('.js-clear-notifications').on('click',function() {
$(this).removeClass('AlertNotificitions');
}
The new way, if you have already defined the variable, the proper way to delete it from the DOM would be:
var elem = document.getElementById("myDiv");
elem.remove();
But if you are just beginning out, .remove would be your best opinion.

JQuery Mobile vclick event only fires once

I'm trying to do a simple button rollover, changing it's icon when it's vclicked, but really don't get why the vclick event is only fired once, can someone shed some light on this? I get the same result if I use "click" or attach the event directly to the button element.
JSFiddle at: http://jsfiddle.net/w7quoyn4/
$('#btnAddToCart').on('vclick', function () {
console.log("btnAddToCart vclick event fired");
if ($(this).attr('data-icon', "plus")) {
$(this).attr('data-icon', "minus").button().button("refresh");
} else {
$(this).attr('data-icon', "plus").button().button("refresh");
}
});
Thanks in advance :)
There are two issues in your code.
First, the conditional expression $(this).attr('data-icon', "plus") invokes the setter form of attr(), which will always return the jQuery object its is called on. Since objects are always true in a boolean context, your else branch will never be taken.
To fix that, you could invoke the getter form of attr() and compare the result:
if ($(this).attr("data-icon") == "plus") {
// ...
}
Then again, the calls to button() are the heart of the matter. The appropriate method to use would be buttonMarkup(), but it is deprecated since release 1.4 (and will be removed in 1.5).
The actual solution is to add and remove the appropriate classes yourself, as in:
$(document).on("vclick", "#btnAddToCart", function () {
console.log("btnAddToCart vclick event fired");
$(this).toggleClass("ui-icon-plus ui-icon-minus");
});
You can see the results in this updated fiddle.

jQuery syntax for if checking if class along with keydown

I am writing an interaction and need a bit of syntax help on one element:
Need to check "IF" a class is present on a div
<div class="something">
and the "Enter" key is pressed (key 13)
switch (window.event.keyCode) {
case 13:
window.location.href = 'http://google.com';
break;
}
then run a function
$('#thing').addClass('that');
What would proper jQuery or JS Syntax be for something like this?
So to clear things up: I have a div with classes that are changing. I am trying to get the browser to detect when said class is present on the dive "AND" the enter button is pressed, then run a function.
Thanks!
Here is a working JSFiddle
You can check for the class within your keypress function:
$(function() {
$(window).keypress(function(event)
{
if ((event.keyCode == 13) && ($('div').hasClass('this')))
{
$('#thing').addClass('that');
}
});
});
You may want to change the generic div to check whether a certain div has the class by its id
if($('#thing').hasClass('that')) { // your code };
Simple as that. Check out the jQuery docs some time. Usually if you need to do anything, there's a function for it already.
You are probably looking for the jquery function .hasClass()
https://api.jquery.com/hasClass/
like
if($("#thing").hasClass("something")){
$("#thing").addClass("that");
}
I don't completely understand understand what you are trying to do to incorporate it in your code.

Event delegation in jQuery, how to do it?

In JavaScript i used to use event delegation like this :
someDiv.addEventListener('click', function(evt){
if(evt.target.id == "#someChild"){
// Do something..
} else if(evt.target.id == "#anotherChild"){
// Do something else..
}
}, false);
What's the equivalent of this in jQuery? i know about .on() but how to use it in event delegation ? i mean is this how is it done :
someDiv.on('click, '#someChild, #anotherChild", function(evt){
if($(this).is("#someChild")){
// Do something..
} else if($(this).is("#anotherChild")){
// Do something else ..
}
});
But wouldn't it be just the same as in vanilla JavaScript ? I want to know if there's a better way to achieve it. And if this is the only way, what's the benefit of jQuery way over JS one ?
You can do:
$(someDiv).on('click', '#someChild, #anotherChild', function(){
if(this.id ==='someChild'){
// Do something..
} else if(this.id === 'anotherChild'){
// Do something else ..
}
});
Or create two event handlers if you do different things for both elements anyway:
$(someDiv).on('click', '#someChild', function(){
// Do something..
}).on('click', '#anotherChild', function() {
// Do something else ..
});
But wouldn't it be just the same as in vanilla JavaScript ? I want to know if there's a better way to achieve it. And if this is the only way, what's the benefit of jQuery way over JS one ?
Of course it's basically the same, jQuery just makes your life a bit easier by providing a wrapper around the DOM API, but it does not change how the DOM works.
There is a difference though, namely that this will refer to the element matched by the selector, not to the element the handler is bound to.
In general, the advantage is that the jQuery code is more cross-browser compatible than using addEventListener.
With jQuery you'd do it like this:
function onButtonClick(e) {
//this = the button that was clicked
}
$(document.body).on('click','button',onButtonClick)
You can read the docs here
You could start here, if this element is created dynamically, and not there on page load
$(document).on('click', '#someChild', function(evt) {
// Do something..
});
If the element is created before the page is rendered then this will work
<input type="button" onclick="fnClickfn();" id="xxx" />
EDIT:
Oh, also .on only works in later versions on jQuery (I think 1.6 and above), so make sure you aren't using an old version that would require .live and .die.

jQuery not working after executing once

As you can see here, my little jQuery script isn't working after running twice, and I'm getting a weird error. Do any of you happen to know what's going on/how to fix it? That would be fantastic if you did!
Thank you!
Connor
You are only binding the keypress event on the first .focus element. Once you remove it, it will no longer receive keypress events.
Change this line
$(".focus").keypress(function(event) {
To
$(".focus").live("keypress",function(event) {
jQuery .live() attaches a handler to the event for all elements which match the current selector, now and in the future.
Also, you need to add this after the line above below to prevent unexpected behavior:
if (event.which == '13') {
event.preventDefault(); < stop the enter keypress
You're removing the element for which you're adding the initial keypress event handler. A quick fix would be to take out the event handler into a function and reattach it to your newly added element:
function handleKeyPress(event) {
if (event.which == '13') {
var itemToAdd = $(".focus").val();
if (itemToAdd != ""){
$(this).remove();
$(".active-li").append(itemToAdd);
$("#wrapper ul").append("<li class='active'><input type='text' class='root focus' /></li>");
$(".active-li").removeAttr("class");
$(".active").removeClass("active").addClass("active-li");
$(".focus").keypress(handleKeyPress).focus();
}
}
}
$(".focus").keypress(handleKeyPress);
But I must say, this looks like a very inefficient way to achieve what you're trying to do here... Think of an alternative solution where you don't have to remove your input element (just insert the new <li> before it).

Categories

Resources