0

I'm sorry if this is a stupid question, but I really don't know :(


Consider the code below:

    function myTogglerFunc() {
      $("h1").toggleClass("fave");
    }

    $(function () {
      $("#button").click(myTogglerFunc);
    })

This does what I want it to do pretty easily. Notice the first function is a simple Javascript function, but the second one is a jQuery function because it is within $().

But I thought, hm, the second function doesn't need to be a jQuery function. It can just be a regular Javascript function like the first one, and I changed my code to:

    function myTogglerFunc() {
      $("h1").toggleClass("fave");
    }

    function () {
      $("#button").click(myTogglerFunc);
    }

and I got an error message.
I really don't know why this is wrong. If anyone can explain, please do. Thank you!

CodingMee
  • 65
  • 8
  • Also, https://stackoverflow.com/questions/3528509/document-readyfunction-vs-function – Sam Axe Jun 16 '20 at 03:18
  • What was the error message? – Sean Jun 16 '20 at 03:18
  • 1
    Keep in mind that jQuery is a JavaScript library-- at no point is it transpiled from a separate "jQuery language" into JS-- you're just leveraging the jQuery API inside of JavaScript to help you accomplish things. To this end, there is really no such thing as a "jQuery function"-- any function you write in JavaScript is a JavaScript function. The question only becomes "am I using jQuery in this particular JavaScript function". The syntax you are seeing there is simply a shorthand for the jQuery document ready. – Alexander Nied Jun 16 '20 at 03:19
  • function () will throw the error because it does not have the function name – Tony Dong Jun 16 '20 at 03:25
  • @TonyDong Yep, you were right, once I added a function name, the error went away... but I thought function names were optional for JavaScript? – CodingMee Jun 16 '20 at 03:29

0 Answers0