How can I make this repetitious jQuery less so?

I have 4 blocks of jQuery that look like this:

$('#aSplashBtn1').click(function(){
  $('#divSliderContent div').hide();
  $('#divSplash1').fadeIn('slow');
  return false;
});
$('#aSplashBtn2').click(function(){
  $('#divSliderContent div').hide();
  $('#divSplash2').fadeIn('slow');
  return false;
});
$('#aSplashBtn3').click(function(){
  $('#divSliderContent div').hide();
  $('#divSplash3').fadeIn('slow');
  return false;
});
$('#aSplashBtn4').click(function(){
  $('#divSliderContent div').hide();
  $('#divSplash4').fadeIn('slow');
  return false;
});

I've tried learning more about javascript arrays and for loops but when I try to implement it into this code it only ends up working for the number 1 block. Could someone show me how they would accomplish optimizing this?

Answers


A variation on Sosh's answer

$('#aSplashBtn1').click(hideAndFadeIn('#divSplash1'));
$('#aSplashBtn2').click(hideAndFadeIn('#divSplash2'));
$('#aSplashBtn3').click(hideAndFadeIn('#divSplash3'));


function hideAndFadeIn(splash){
    return function() {
        $('#divSliderContent div').hide();
        $(splash).fadeIn('slow');
        return false;
    };
}

If the clickable items are siblings, you can do:

$('#aSplashBtn1').siblings().andSelf().click(function(e){
    $('#divSliderContent div').hide();
    $('#divSplash'+e.target.id.substr(e.target.id.length-1)).fadeIn('slow');
    e.preventDefault();
});

var $divSlider = $("#divSliderContent div");
$('*[id^=aSplashBtn]').live('click', function(e){
    // Get the number from the id of the clicked element
    var id = this.id.match(/^aSplashBtn(\d+)$/)[1];

    $divSlider.hide();

    $("#divSplash" + id).fadeIn('slow');

    // Preferred as opposed to return false
    e.preventDefault();
});

This will set a single handler that will match every element with an id that starts with aSplashBtn. Your id's could go as high as you wanted (i.e. #aSpashBtn100) and it would still pair with the correct div#divSplash100.

Also, I cached #divSliderContent div in its own variable since you don't want jQuery to 'look it up' again on each click.


Need Your Help

Errors in cstdint: No member named xxx in global namespace

c++ macos

What can cause errors like these? I added an empty project to Xcode, added /usr/local/lib in the Header Search Paths, and added some opencv libraries. Building gave these errors:

Parse error: syntax error in PHP

php

I try to store a string to a PHP variable. But it shows an error "Parse error: syntax error, unexpected '='"