How to create functions in jQuery?

Asked

Viewed 20,561 times

8

I would like to know the correct way, following good practices, to create functions in jQuery.

I’ve used it like this:

var focusToEnd = function() {
    ...
}

And also so:

; (function($) {
    $.fn.focusToEnd = function() {
        return this.each(function() {
            var v = $(this).val();
            $(this).focus().val("").val(v);
        });
    };

But I don’t know, which of the two ways is right, or if there’s no difference.

  • 2

    What exactly do you want? Create a function that can be called as $('#seletor').minhaFuncao(), or called independently, as in minhaFuncao()?

  • 1

    http://learn.jquery.com/javascript-101/functions/

  • @bfavaretto ai whatever, I want to know just what good practice using jQuery.

  • 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

3 answers

23


$.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.

  • So just create as many functions as I want within the scope of $.fn.extend({ or I have to start several $.fn.extend({, being one for each function?

  • You can create more than one function at once, such as $.fn.extend({ funcao1: function() { ... }, funcao2: function() { ... });. But remember to consider whether it makes sense to create the function next to jQuery.

  • because, that has some though?

  • @Patrickmaciel It only makes sense to add jQuery.fn functions that manipulate DOM nodes (collection selected via jQuery and available in their function as this). That’s a little confusing in your question, can’t tell if it’s clear to you or not.

10

jQuery is only a library built with Javascript, and functions are a language feature, not jQuery.

His two examples are valid ways of creating functions, and there are still other ways. While ways of creating functions, they are not so different. But their use is, yes, quite different.

In the first case, var focusToEnd = function... you are creating a function and assigning to the variable focusToEnd. From this point, you can call your function with focusToEnd().

In the second case, you are "hanging" the function on $.fn, which is a special object of jQuery used as prototype of all objects created with $('um_seletor_aqui'). Function cannot be called with focusToEnd(), only as a jQuery object method - for example, $('um_seletor_aqui').focusToEnd().

In the second case, therefore, you are creating a jQuery plugin. In the first, a common function.

2

The syntax for creating a function is:

function nomeDaFuncao(){
     //conteúdo...
}

after that you can call her in several ways...

Browser other questions tagged

You are not signed in. Login or sign up in order to post.