$.fn.extend
To extend jQuery (read plugin) there is the function jQuery.fn.extend().
Example:
$.fn.extend({
alertar: function () {
return this.each(function () {
alert($(this).text());
});
},
exibirNoConsole: function () {
return this.each(function () {
console.log($(this).text());
});
}
});
$('.comment').alertar(); // exibe os textos dos elementos com a classe '.comment' como alert
$('.comment').exibirNoConsole(); // mesmo do acima só que no console
Beware not to confuse with the function $.extend that works for any object. $.fn.extend(funcoes)
is equivalent to $.extend($.fn, funcoes)
.
When extend the jQuery?
jQuery is a Javascript library that offers you handling of HTML documents (DOM), events, animation, ajax, Javascript utility methods in general, among others.
If the function you’ve developed does sense be close to this range of features consider connect it next to jQuery (via the method shown above). Think of your function as a plugin.
Javascript != jQuery
Note that I answered how to create a function on jQuery (the library) and not in Javascript (the language).
Javascript is very simple:
function hello() {
alert('Hello World');
}
I noticed by your question that there was some confusion between what is a Javascript function and a jQuery function. Do not exist jQuery functions, are all Javascript at the end of the accounts. What is possible is to attach a function developed by you to the jQuery object (the famous $
).
I recommend studying the basics of Javascript before using a library (especially if it’s extensive like jQuery) so you don’t mix the concepts in the learning process.
What exactly do you want? Create a function that can be called as
$('#seletor').minhaFuncao()
, or called independently, as inminhaFuncao()
?– bfavaretto
http://learn.jquery.com/javascript-101/functions/
– Zignd
@bfavaretto ai whatever, I want to know just what good practice using jQuery.
– Patrick Maciel
I was the other day kind of aimless in the js, until I found this guide. Just to add to the post, since you spoke of best practices, maybe a good style suits you too. https://github.com/armoucar/javascript-style-guide
– Marcos Freitas