Tuesday, January 14, 2014

JQuery : Declare a function



Method 1: The Javascript way

The simple way to declare a  function in javascript:


function callMe (count) {
     return (count+5);
}

console.log(callMe(13));
//output: 18

Disadvantage: If you wanted a quick function to test something then maybe that’s the only occasion you would use this. It’s not good coding and doesn’t promote code reuse.


Method 2: Creating your JQuery function

The simple way to declare a  function in javascript:


<div id="mydiv">i am here</div>

jQuery.fn.extend({
    mytext: function () {
        var text = $(this).text();
        var mytexts = '';
        var toggle = true; //lower/uppper toggle
            $.each(text, function(i, nome) {
                mytexts += (toggle) ? nome.toUpperCase() : nome.toLowerCase();
                toggle = (toggle) ? false : true;
            });
    return mytexts;
    }
});

console.log($('#mydiv').zigzag());
//output: #1 i aM HeRe

//chained example
console.log($('#mydiv').zigzag().toLowerCase());
//output: #1 i am here


Method 1: Functions in custom namespaces

If your writing functions in a custom namespace you must declare them in this way. Extra functions can be added to the namespace you just need to add a comma after each one (except the last one!).


JQUERY4U = {
    callme: function(count) {
        return (count + 5);
    }
}
//function call
JQUERY4U.callme(13);

Reference post: Full credit goes to the original post, which made the topic so easy to understand (visit for more details).


No comments:

Post a Comment