-3

I'm looking through a website's source code because I'm trying to learn to some basic Javascript. I understand the first part:

function count() {
  ...
}

I know that the function is called count, and doesn't take any arguments. The next function I don't understand:

$(function(){
  ...
});

Is the function called 'function'? And why is there a '$' symbol at the beginning. I've tried searching the internet, but google just ignores the '$'s and brackets and just searches for 'function'.

In addition, another thing I don't understand; the website has a single button that, when pressed, plays an audio file. The button is set up like so:

<a href="javascript:void()" id="button">
<img src="img/button.png" border="0">
</a>

What does javascript:void() do?

I'm sorry this isn't really a programming question, but I'm trying to learn Javascript and i figured I might have a look what other people are doing.

user2397282
  • 3,798
  • 15
  • 48
  • 94

2 Answers2

3

$ is the name (actually a reference to) of a function defined by the very popular jQuery library.

$( ) is calling the $ function

Inside the parenthesis you have an anonymous function definition.


$(function(){ console.log('test'); });

is pretty much the same as:

function nameNotImportant() { console.log('test'); }
$(nameNotImportant);

but it's more concise and you don't have to think of a name for that function.


As you probably noticed, nameNotImportant is not called. A reference to it is passed as parameter to the $ function to do as it wants with it, including call it. That is exactly what the $ function does when passed a function as parameter to it: it calls that function when the DOM is ready to be interacted with.


<a href="javascript:void()">

When an <a>nchor is clicked, the default action performed by the browser is to navigate to its href attribute. If you want it to not do that, you have to somehow interfere with the mechanism, for example by setting the href attribute to execute some javascript code that does nothing. I wouldn't consider it an example of good programming, but that is what it is used for.

Tibos
  • 27,507
  • 4
  • 50
  • 64
0

I'm assuming you know that $ is an alias to jQuery.

$(function() {
    // ...
});

is passing an anonymous function to the $ function, which can take a callback function. This function is run when the DOM is ready, so the more verbose form of this is

$(document).ready(function() {
    // ...
});

In addition,

javascript:void()

is used to simply return undefined for a URL--aka the browser does not navigate to a page when you click on the link. javascript:void() is often used to allow the developer to bind JavaScript click events to the <a> tag.

Community
  • 1
  • 1
Kevin Ji
  • 10,479
  • 4
  • 40
  • 63