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?...
mouseenter is a function. Similar to:
var element = {elm: document.getElementById('test')};
element.mouseenter = function(func) {
element['elm'].addEventListener('mouseenter', func);
};
element.mouseenter(function() {});
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);
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.
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.
Related
Hi I am currently trying to call a function that is saved to a variable, but also has an event handler on it.
col.onclick = function(e){
}
I have not been able to find how to call this kind of set up, and was wondering if it's possible at all, and if it can be done without using jquery.
Help would be nice, thanks in advance.
http://pastebin.com/JJYQeZDG //Code that is the root of the problem.
This code is for a game of checkers, for context.
Simply use () like any other function.
Based on your comments, it looks like you may also have a scoping issue.
I would recommend refactoring your code so your onclick function can be accessed without needed the col object:
var onclick = function(e) {
// note: you will only have "e" if this is invoked as an event callback
};
// later when defining col
col.onclick = onclick;
// ...and later when you want to directly invoke onclick
onclick();
I am trying to display a div on click. The function that is supposed to make the magic happen is:
$(document).ready(function showGogoasa() {
$('.gogoasa-newsletter').show();
});
Unfortunately, it does nothing. Which makes me scratch my head for hours as I have done small things like this in the past and they worked. I am trying to make this modification on the website of a client.
When I check the firebug console it says the following: ReferenceError: showGogoasa is not defined
I tried looking on Google for this kind of error but the similar cases had this kind of issue for not declaring a variable. Well, I do not have any variables.
I am trying to display a div on click.
Your code is running the function on a ready event and doesn't give the error you describe.
Presumably (it would have helped if you had provided a complete test case) you are also trying to bind the function as a click handler, but you can't do that because you have defined it using a function expression and not a function declaration (so it doesn't create a variable called showGogoasa outside of its own scope).
Define the function separately, then assign call it and bind it as a click event handler on the ready event.
$(document).ready(function ready_handler() {
function showGogoasa() { // Define it as a variable in the current scope
$('.gogoasa-newsletter').show();
}
showGogoasa(); // call it now
$("button").on("click", showGogoasa); // call it then
});
Well, I do not have any variables.
That's the problem :)
Functions are first class objects and when you say showGogoasa() that means "Get the value of showGogoasa and call it as a function".
Using jsfiddle or providing more code would have been helpful.
One issue is that you are missing the click event handler. For example when the user clicks on X then Y should happen/show. The following simple example may help you to see how it works:
http://jsfiddle.net/fionaredmond/1vbagj12/
$(document).ready(function(){
$("#showGogoasa").click(function(){
$(".gogoasa-newsletter").show();
});
});
$(document).ready(function() {
$('#idOfYourClickerElement').on('click', function(){
$('.gogoasa-newsletter').show();
});
});
It's for a backbone application,
I'm using Jquery html() function to insert my views templates into the layout everywhere, and I would like to be able to trigger an event each time the html() function of jQuery is called to check the html of the page.
Is there a way to do that ?
( Like App.on('html', blablabla...); )
Thank you !
As Marc B suggested DOM MutationEvents is available on some browsers (not many). By default jQuery does not fire any event when using html, but you can define your own behaviour for this, for example:
(function($) {
var html_ref = $.fn.html;
$.fn.extend({
html : function() {
$(document).trigger( 'html_change' );
return html_ref.apply(this, arguments);
}
});
})($);
It should work, didn't test it though. You can use the same with .text method. Now you can simply use:
$(document).bind( 'html_change', function() {
// Hurray! Html changed!
});
That's the idea, use it as you wish.
AFAIK, the jQuery html() method doesn't fire any subscribable events per se, but you could probably roll your own implementation of a simple Observer pattern. I use this across a large number of projects and it provides a great, clean, lightweight way to encapsulate arbitrary event handling across loosely-coupled modules.
However, this is presuming that you have programmatic control over every time the html() method is called - if not, then this would be more difficult, as there is no callback function to hook into.
I can set the onclick handler using jQuery by calling
$('#id').click(function(){
console.log('click!');
});
Also using jQuery, how can I get a reference to the function which is currently handling the click() event?
The reason is that I have another object and want to set its click handler to the same one as #id.
Update
Thank you for all the suggestions. The problem is that I do not know which function is currently handling the clicks. Keeping track of it would add state to an already complicated template-editing system.
jQuery's .click(function) method adds the function to a queue that is executed on the click event~
So actually pulling out a reference to the given function would probably be hairy-er than you expect.
As noted by others, it would be better to pass in a reference to the function; and then you already have the reference you need.
var clicky = function () { /* do stuff */ };
$('#id').click(clicky);
// Do other stuff with clicky
Update
If you really really need to get it out, try this:
jQuery._data(document.getElementById('id')).events.click[0].handler
Depending on your version of jQuery that may or may not work~ Try playing around with
jQuery._data(document.getElementById('id'))
and see what you get.
Got the idea from this section of the source:
https://github.com/jquery/jquery/blob/master/src/event.js#LC36
if you dont know the name of the function you can use
args.callee
https://developer.mozilla.org/en/JavaScript/Reference/Functions_and_function_scope/arguments/callee
function clickHandle(e){
if($(e.target) == $('#id')) {
$(newTarget).bind('click', clickHandle);
}
}
$('#id').bind('click',clickHandle);
I think this would be the most symantic way of going about it
I'm working on a project where a number of different companies are working on the same site.
The main developer have set up an event - let's call it init - which indicates the page is ready for our code to execute.
They're basically calling it like this:
$(window).trigger('init');
For a number of reasons I won't go into here, we prefer to avoid using jQuery in our own code wherever possible. I tried to bind to it like this:
window.addEventListener('init', function (event) {
alert('hehehehe');
});
But that doesn't seem to work. This works perfectly, though:
$(window).bind('init', function (event) {
alert('hehehehe');
});
Does jQuery use special event objects by default that you can't bind to with plain JS? Am I just doing something stupid?
The docs for bind seem to contain the answer:
Any string is legal for eventType; if the string is not the name of a native DOM event, then the handler is bound to a custom event. These events are never called by the browser, but may be triggered manually from other JavaScript code using .trigger() or .triggerHandler().
There's no native DOM event called 'init':
http://en.wikipedia.org/wiki/DOM_events
Hence "These events are never called by the browser, but may be triggered manually from other JavaScript code using .trigger() or .triggerHandler()"