Without seeing the other two instances of your code, I assume that the
things that vary among them are the two ID selectors and the two text
messages, is that right?

Then it's a simple matter of turning your code into a function:

function slider( idShade, idTrigger, textView, textHide ) {
    var $shade = $('#'+idShade);
    $shade.hide();
    $('#'+idTrigger).click( function () {
        $shade.animate({
            height: 'toggle',
            opacity: 'toggle'
        }, 'slow');
        var $this = $(this);
        $this.text( $this.text() == textView ? textHide : textView );
        return false;
    });
}

$(document).ready(function() {
    slider(
        'topShade', 'trigger_sitemap',
        'View Site Map', 'Hide Site Map'
    );
    // and simlarly for your other two instances
});

Also I changed your double quotes to single since there was a mix of them.
It's a good idea to pick one (I strongly recommend single quotes in JS code)
and use it consistently.

-Mike

> From: arthaus
> 
> On a page, I have THREE slide-fade animation. And currently 
> I'm replicating three instances the following code.
> 
> $(document).ready(function() {
>       $('#topShade').hide();
>       $('#trigger_sitemap').bind("click", function () {
>               $('#topShade').animate({
>                       height: 'toggle',
>                       opacity: 'toggle'
>               }, "slow");
>               var $this = $(this);
>               var trigger_txt_sitemap = $this.text();
>                       if (trigger_txt_sitemap == 'View Site Map') {
>                               $this.text('Hide Site Map');
>                       } else {
>                               $this.text('View Site Map');
>                       }
>               return false;
>       });
> }); // document.ready
> 
> How can I efficiently rewrite this code? (that will be used multiple
> instances)
> 
> Thanks in advance,
> Arthur

Reply via email to