Tim Joyce
Tim Joyce

Reputation: 4517

How can I shorten this code jquery

    $( "#nextFrom1" ).click(function(){
            $( "#widget01" ).fadeOut( "slow", function(){
                    $( "#widget02" ).fadeIn( "slow" );
                });
        });
    $( "#nextFrom2" ).click(function(){
            $( "#widget02" ).fadeOut( "slow", function(){
                    $( "#widget03" ).fadeIn( "slow" );
                });
        });
    $( "#prevFrom3" ).click(function(){
            $( "#widget03" ).fadeOut( "slow", function(){
                    $( "#widget02" ).fadeIn( "slow" );
                });
        });
    $( "#prevFrom2" ).click(function(){
            $( "#widget02" ).fadeOut( "slow", function(){
                    $( "#widget01" ).fadeIn( "slow" );
                });
        });

Please guide me in the right direction of shortening this code. Objects maybe?! This is just a small chunk of the ever repeating anonymous functions.

Upvotes: 1

Views: 90

Answers (4)

Eli
Eli

Reputation: 17815

Create a jQuery plugin. Here is something to get you started:

(function($) {
    $.fn.directWidget = function(options) {
        var defaults = { 
            /* default options go here */
            hiding: null,
            showing: null,
            speed: 'slow'
        };
        var settings = $.extend({}, defaults, options);

        return this.bind('click.directWidget', function(e) {
            $(settings.hiding).fadeOut(settings.speed, function() {
                $(settings.showing).fadeIn(settings.speed);
            });
        });
    };
})(jQuery);

You can then call like so:

$('#nextFrom1')
    .directWidget({ hiding: '#widget01', showing: '#widget02', speed: 'slow' });

Upvotes: 1

Mutation Person
Mutation Person

Reputation: 30498

Create a functiont to do the binding for you, passing in your respective ids:

function BindClick(clickId, widgetId1, widgetId2){
    $( clickId ).click(function(){
            $( widgetId1).fadeOut( "slow", function(){
                    $( widgetId2 ).fadeIn( "slow" );
                });
        });
}

And calling:

BindClick("#nextFrom1", "#widget01", "#widget02");
//etc

Upvotes: 4

Mike Thomsen
Mike Thomsen

Reputation: 37506

Maybe something like this:

function makeClickHandler(fadeOut, fadeIn){
    return function(){
        $( "#widget" + fadeOut ).fadeOut( "slow", function(){
            $( "#widget" + fadeIn ).fadeIn( "slow" );
        })
    };
}
$( "#prevFrom2" ).click(makeClickHandler("02", "01") );

Upvotes: 3

Pranay Rana
Pranay Rana

Reputation: 176896

Create jquery plugin rather than repeating code

example : http://pranayamr.blogspot.com/2010/11/jquery-plugin-how-and-when-to-use-it.html

Upvotes: 2

Related Questions