Byff
Byff

Reputation: 1

Question about javascript event handler syntax

My question appears to have been deleted yesterday before it could be answered, so I'm starting a new thread on the subject.

I've been trying to find cross-browser resize javascript, and ran across this syntax in one answer posted here:

$(window).resize(function()

I'm afraid I don't understand the syntax $(window).. Is that something specific to jquery?

Upvotes: 0

Views: 221

Answers (5)

josh3736
josh3736

Reputation: 144902

Let's break down $(window).resize(function() { });:

  • $ (an alias for jQuery) is simply the name of a JavaScript function. In this case, it's the jQuery object constructor function.

  • (window) - since we're calling a function, parameters are enclosed in parentheses. The jQuery function takes a number of parameters (selector strings, DOM element[s], other jQuery objects, and HTML strings). Here, we're passing the DOM window object, since we know it fires the onresize event that we want to bind to.

  • . - the jQuery() function returns a jQuery object—which has many methods and properties—and we use a period to access those methods.

  • resize() is a method of the jQuery object. Depending on the arguments you pass to it, it either triggers the resize event (when you pass no arguments) or binds a new event handler to the event (when you pass a function reference, like we are here). Bound event handler(s) are called each time the event is triggered by code or by the browser.

  • function() { } is the syntax for an anonymous function. The code you would write inside the { } gets executed each time the function is called. In this case, the function is called when the resize event is triggered.

Upvotes: 1

guildsbounty
guildsbounty

Reputation: 3361

Yes, this is specific to jQuery. Which is cross browser and free to download. I would suggest using jQuery for this since it takes care of all the cross browser difficulties for you. The $(window) is shorthand for jQuery(window) which selects the browser window and any options, events, and anything else that is associated with it

Upvotes: 0

lonesomeday
lonesomeday

Reputation: 237845

You added your question as an answer to an old question. This is the right way to do it!

$(window) is jQuery syntax for creating a jQuery object that contains the window object. Certain events are triggered on this, for instance resize, load, etc.

This syntax adds a resize handler to the window.

Upvotes: 1

Mike Samuel
Mike Samuel

Reputation: 120496

Yes. See http://api.jquery.com/jQuery/

Upvotes: 0

Pointy
Pointy

Reputation: 413712

The "$" character in JavaScript can be used freely in variable and function names. Thus, jQuery uses the identifier "$" as an alias for the "jQuery" function.

You can do this yourself:

var my$variable = "hello world";
alert(my$variable);

Or

function my$function() { ... }

Upvotes: 0

Related Questions