1

I am trying to build a simple menu using jquery and it won't work. I'm getting a NaN error when trying to get the id and class of this. The elements in question have both an id and a class. What's going on?

   $(document).on("click", function()
    {
        if($(this).attr("class") != "userOptButtons" && $(this).attr("id") != "usernameDisplay")
            $("#userMenu").animate({"top": "-198"});
    });

3 Answers 3

4

because this refers to the document object, if you want to target the actual element clicked then use event.target

$(document).on("click", function (e) {
    if (!$(e.target).hasClass("userOptButtons") && e.target.id != "usernameDisplay") {
        $("#userMenu").animate({
            "top": "-198"
        });
    }
});
Sign up to request clarification or add additional context in comments.

2 Comments

Awesome! Could you elaborate a little? according to the event object what is going on?
@CraigPatrickLafferty since you are binding the handler to document object, this inside the event handler will refer to the document object. The event handler will receive the event object as an argument which will have a property called target which will refer to the actual element that was clicked.
1

$(this) is referencing "document", the entire DOM, not your menu item that is clicked.

Unless you want to handle clicks on anything in the DOM in a single event handler, you're probably better off with an event handler just for your menu. Say each item in your menu has the same class name, "menuitem", then you could do something like this:

$('.menuitem').on('click', function (e) {
    // now you can use $(this) in here to reference the item clicked
    // plus everything else here can be custom just for your menus
}

If you're going with a single handler, as shown in your existing code, you need to reference the item clicked instead like this instead of using $(this):

$(e.target)

See http://api.jquery.com/event.target/ for more details.

Comments

0

you could also use this syntax this adds the on click event only to the DOM objects with an id of "usernameDisplay" and a class of "userOptButtons"

$("#usernameDisplay .userOptButtons").on("click", function () {
        $("#userMenu").animate({
            "top": "-198"
        });   
});

4 Comments

$(document).find(".userOptButtons") ? why not just $(".userOptButtons")
I want the menu to disappear when it loses focus but if i clicked on a button in the menu then the button that was previously focused would lose its focus and the menu would disappear.
I want the animation to occur only when the click IS NOT on the menu buttons.
Oh, I understand now. Arun P Johny has the best solution

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.