$. 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
Pay attention not to be confused with the $ .extend function that works for any object. $.fn.extend(funcoes)
is equivalent to $.extend($.fn, funcoes)
.
When extend jQuery?
jQuery is a JavaScript library that offers you manipulation of HTML documents (DOM), events, animation, ajax, JavaScript utilities in general, among others.
If the function you have developed makes sense be close to this range of functionalities consider joining it next to jQuery (via the method shown above). Think of your role as a plugin .
JavaScript! = jQuery
Note that I have answered how to create a function in jQuery (the library) and not in JavaScript
In JavaScript it's very simple:
function hello() {
alert('Hello World');
}
I noticed from your question that there was some confusion between what a JavaScript function is and a jQuery function . There are no jQuery functions , they are all JavaScript at the end of the day. What is possible is to link a function that you have developed to the jQuery object (the famous $
).
I recommend studying the basics of JavaScript before using any library (especially if extensive like jQuery) so you do not mix the concepts in learning.