jQuery syntax for if checking if class along with keydown - javascript

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.

Related

toggleClass() only toggling to one class

I'm having trouble with a jQuery/Angular function being executed on click.
<a ng-click="like()" href="#" class="like like--yes"></a>
Basically, when a click occurs on a like button, I want to toggle the like--yes and the like--no classes. I've inspected the DOM while clicking, and once it has been set to like--no, it refuses to change back.
$scope.like = function() {
$('.like--no').toggleClass('like--no like--yes');
$('.like--yes').toggleClass('like--yes like--no');
}
I need two different functions so to speak, as I'm adding different animations depending on whether it's a like/unlike.
Any idea where I'm going wrong? There's more to it, but I've stripped some of the unnecessary code out for clarity.
Thanks.
I see that you are using AngularJS so instead of using jQuery, why not use ngClass?
Like this:
<a ng-click="toggleLike()" ng-class="{'like--yes': like, 'like--no': !like}">Hello World!</a>
Plunkr
It seems there is a logical issue
$scope.like = function() {
$('.like--no').toggleClass('like--no like--yes');
$('.like--yes').toggleClass('like--yes like--no');
}
Case:- first line changes like--no to like--yes and after that second line changes like--yes to like-- no again.
You should try .hasClass() function to check whether element has class then use toggle.
It seems like the second line is overwritting the first one.
It sets the class to like--yes and the second line catches the like--yes and set it to like--no everytime.
Try something like:
$scope.like = function() {
if( $('.like').hasClass( 'like--yes' ) ) {
$('.like').removeClass( 'like--yes' );
$('.like').addClass( 'like--no' );
} else {
$('.like').removeClass('like--no');
$('.like').addClass('like--yes');
}
}
Maybe you need change $('.link') to $(this) to get the actually clicked element.
It's generally frown upon to deal with DOM jQuery-style inside an Angular's controller, which is what you attempted to do and the other answers suggested.
Just have a variable that reflects the like state (you can set it directly in the View or inside the $scope.like() function and use ng-class to toggle the class:
<a ng-click="like=!like" href="#" ng-class="like ? 'like--yes':'like--no'"></a>
try this
$('.like').on('click',function(e){
e.preventDefault();
$(this).toggleClass('like--no like--yes');
if($(this).text() == 'like'){
$(this).text('unlike');
}else{
$(this).text('like');
}
});
and html
like
JSFIDDLE

How do I change cursor on keypress (Ctrl) in JQuery?

Using jQuery, I would like to change the cursor on page when any key is pressed (for example Ctrl).
Simple task, however I can not get make it work...
This was my first idea, obviously - does not work:
$(document).on('keydown',function(){
$(document).css('cursor','wait');
});
Any idea what is wrong?
Think what you want is something like this:
$('body').css('cursor','wait');
You can't apply CSS to the document. Also if you wanted to only apply this css to the CTRL key press you could do:
$(document).on('keydown', function (event) {
if (event.ctrlKey) {
$('body').css('cursor', 'wait');
}
});

Clear input box on click with Jquery

I have a simple code that I'm trying to wrok into my website to clear a textbox with a default value, when a user click on it, the default value should clear out so that the user can enter his/her value. Here is what I have but I'm not sure if its correct since its not working. I just started on JQuery
$(document).ready(function()
{
$('#startDateBox').click(function()
{
if(('#startDateBox')=='Beginning')
{
$('#startDateBox').val('');
}
})
});​
You missed the first .val(), and the $ in front of the ('#startDateBox') on the same line.
You could also use $(this) to reference the textbox, as within that function this refers to the textbox DOM element itself. Wrapping it with the jQuery function $() gives you access to all the framework's goodies.
$(document).ready(function()
{
$('#startDateBox').click(function(){
if($(this).val() == 'Beginning')
^^^^^^ Here
{
$(this).val('');
}
})
});​
You're wrong in this part:
if(('#startDateBox')=='Beginning')
First, you missing $.
Second, I think you want compare the startDateBox value, then use val().
Try this:
$(document).ready(function()
{
$('#startDateBox').click(function()
{
if($('#startDateBox').val()=='Beginning')
{
$('#startDateBox').val('');
}
})
});​
Well, if(('#startDateBox')=='Beginning') will always be false...
I think you meant something more like:
if($('#startDateBox').val() == 'Beginning')
I wrote a very small jquery plugin for this purpose recently:
https://gist.github.com/rmcvey/5136582
$('#input').placeholder("Placeholder Text");
if($('#input').val() === $('#input').placeholder()){ return false; }
I would suggest for HTML5 browsers use this
<input type="text" id="Beginning" placeholder="Beginning" />
if($('#startDateBox').val() =='Beginning')
this is the line that needs to be changed
also
$('#startDateBox').on("focus", function()
{
// code here
the click will not handle hitting tab until that text box is focused

Want to display "True" and "False" buttons

I have a grid of buttons where user opens up the gird by clicking on the (Open Grid) link and then clicking on a button in that grid. What I want to do is that if user clicks on the "True or False" button, then it should output buttons "True" and "False" underneath the "Number of Answers" textbox. But it is not displaying anything. What am I doing wrong?
The code is here:
$(".gridBtns").click(function() {
var clickedNumber = this.value;
$('.answerBtns').each(function (index) {
if (index < clickedNumber)
$(this).show();
else
$(this).hide();
});
if (document.getElementsByClassName("gridBtns").value == "True or False")
{
document.getElementId("answerTrue").style.display = "block";
}
});
Full code is in jsfiddle, click here
Instead of this:
if (document.getElementsByClassName("gridBtns").value == "True or False")
{
document.getElementId("answerTrue").style.display = "block";
}
Try this:
if (this.id=='btnTrueorFalse') {
$('#answerTrue').show();
$('#answerFalse').show();
}
Besides the 1/many error already mentioned in another post, it looks like the original is just looking for the wrong property in the wrong place.
getElementsByClassName returns a NodeList (which acts like an array), not a single Element.
The jQuery code to equal your code above would be
if($('.gridBtns').val() == 'True or False'){
$('#answerTrue').show(); //you may also use .css() for it, but show() has the same result
}
I've been seeing this code here for a while now:
If you use jQuery, use it. Doing document.getElementById(..) suddenly is just nonsensical. Just use jQuery selectors everywhere, and methods (f.i. .addClass(..) instead of .className = ..). jQuery is the way you access your DOM, using a mix is just confusing.
Also, I notice most of your problems with this Ui stem from the fact that:
It is a bad UI (no offense, just think about it)
You use the UI for storing state. Don't do that. UI should be dependent on state, not the other way around.

A quick question about keypress and jQuery

$(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) {
// ...
});

Categories

Resources