Reputation: 1208
I was looking over some code a few minutes ago and this confuses me.
$("nav a").mouseenter(function() {
audio.play();
});
I know '$' is jQuery for document.getElementById(""); and mouseEnter is an event handler for 'nav a' but how is the function assigned to the event? It doesn't have any assignment operator '='?
I don't know to much about jQuery right now as I'm trying to completely get JavaScript down. So when I went to modify the code to be pure JavaScript it doesn't seem to work...
document.getElementById("playAudio").onclick(function () {
audio.play();
});
I don't understand why? I figured it was the same code?...
Upvotes: 1
Views: 83
Reputation: 26837
You're passing a function object (created with a function expression) to jQuery.mouseenter
, and jQuery takes it from there.
FYI, part of what you're trying to get down here is the Document Object Model (DOM). You're trying to make the code pure JavaScript + DOM API. It's good to learn the fundamentals of both JS and the DOM, but be aware that jQuery smoothes out many inconsistencies in browsers' implementations of the DOM, such as registering event listeners.
Upvotes: 0
Reputation: 11
mouseenter is a function. Similar to:
var element = {elm: document.getElementById('test')};
element.mouseenter = function(func) {
element['elm'].addEventListener('mouseenter', func);
};
element.mouseenter(function() {});
Upvotes: 1
Reputation: 3224
The dollar symbol is not just limited to getElementById()
, it the the jQuery object and in your case, is calling the nav
element then grabbing the a
tags within the nav
. After grabbing the element(s), it then attaches the event anonymously, allowing the function to run whenever the event is fired.
Upvotes: 0
Reputation: 5384
The function is passed, and the function is anonymous (doesn't have a name).
You could also do:
function foo() { audio.play(); }
$('nav a').mouseenter(foo);
Upvotes: 0