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
    • 80
    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);
    }
    console.log(multiply(5,2));
    //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.

    (function($){
    
    // 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
    		$(this).css({'background-color':'orange'});
    		
    		// add a message
    		var msg = 'Danger high voltage!';
    		$(this).prepend(msg);
    	}
    	catch(e) 
    	{
    		console.log(e);
    	}
    	
        // preserve return value (probably the jQuery object...)
        return ret;
    }
    
    // run the $.fn.each function as normal
    $('p').each(function(i,v)
    {
        console.log(i,v);
    });
    //output: all paragrahs on page now appear with orange background and high voltage!
    
    })(jQuery);

    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
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
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: