Question

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!

Was it helpful?

Solution

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

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top