Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
  • How to declare functions in jQuery

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 308
    Comment on it

    1. The basic JavaScript function

    The simplest way to declare a function in JavaScript. In below example. we have written a simple function called abcd(x,y) which is simply taking two parameters x and y,.

    function abcd(x,y) { 
    return (x * y); 
    console.log(multiply(5,2)); //output: 10

    2. JavaScript functions for get/set

    If you want a private utility for getting/setting model's values then you can declare a function as a variable like this code below

    var multiply = function(x,y) {
         return (x * y);
    //output: 10

    3. Create your own jQuery function

    This is the best way to declare functions in your own way. jQuery.fn is just an alias for jQuery.prototype.In this method we have to return the element so that we can combine jQuery functions together.

    // maintain a to the existing function
    var oldEachFn = $.fn.each;
    $.fn.each = function() {
        // original behavior - use function.apply to preserve context
        var ret = oldEachFn.apply(this, arguments);
    	// add custom behaviour
    	try {
    		// change background colour
    		// add a message
    		var msg = 'Danger high voltage!';
        // preserve return value (probably the jQuery object...)
        return ret;
    // run the $.fn.each function as normal
    //output: all paragrahs on page now appear with orange background and high voltage!

    There are some more methods too to declare functions in jQuery. The above ones are easy and the best one to learn.



 0 Comment(s)

Sign In

Sign up using

Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: