jQuery Dollar Sign Confusion

10,575

Solution 1

A dollar sign ($) is actually an alias for jQuery function. And according to the documentation, if you pass a callback as an argument to this function, it will be executed when the DOM is ready.

When it comes to the second part of your question (about why the second part of the code is not working): just check the selectors. For me it is working perfectly (see jsfiddle - it is without .button() method, because I am not loading jQuery UI), so this may be caused by incorrect selectors.

Solution 2

What you are doing should work so long as your selector text "#listitems tr" has something valid to select.

You can test by doing ... if the result is 0 that means jQuery did not find any valid items

alert($("#listitems tr").length);

When you make the call

$("a").click(function(evt) { alert("hello world!"); });

You are binding a click event to all <a> tags on your page. You could very well do the same with ...

$("a").click(myFunc);
function myFunc(evt) { alert("hello world!"); }

A click function can be attached to any html element. It does not have to be a button, it could be , , and etc. The element does not even have to be visible though you will only be able to fire the click if you call the actual event by doing ...

$("a").click();

The $("...") is just short hand for typing jQuery("...")

Hopefully this answers your questions.

Share:
10,575
sichinumi
Author by

sichinumi

I am a software developer at Amazon.com in Seattle, Washington. I graduated from the Georgia Institute of Technology in 2013 with a Bachelors in Computer Science, with concentrations in artificial intelligence and human-computer interaction. I enjoy talking to others about code, theory, coding practices, and anything else CS-related. I also enjoy teaching others using my past experiences as foundations.

Updated on July 18, 2022

Comments

  • sichinumi
    sichinumi almost 2 years

    I'm a bit confused regarding the dollar sign in jQuery, and was hoping someone could help me out.

    I have the following function declaration:

    $(function() {
        $( "#create-discussion" ).button().click(function() {
            alert("Clicked");
        });
    
        $( "#listitems tr" ).click(function(event) {
            alert("clicked");
        });
    });
    

    For some reason, the first function declaration for the "create-discussion" button works perfectly; when clicked, a popup appears. However, the second one does not work, and no popup is generated when I click on the table rows.

    Is this some nuance in regards to button onClicks versus table row onClicks? Am I missing something stupidly obvious?

    Also, I think it would help a bunch if someone explained what $(function() {}) actually does, as I'm treating it like $(document).ready(), and I'm not sure if I can do that.