Scott Scott - 4 months ago 9
Javascript Question

JQuery can you show a different element on each subsequent click?

I have a really simple idea... have a button (class="upload") that on each subsequent click, I want it to show a new div, for a set maximum number of times.

For example:

$('.upload').click(function() {
$('.upload_block2').show(0);
}, function() {
$('.upload_block3').show(0);
}, function() {
$('.upload_block4').show(0);
}, function() {
$('.upload_block5').show(0);
$('.upload').hide(0);
});


Obviously the code above does not work...

Is this even possible?

Answer

Declare two global variables, one for the total number of blocks to show, another for the current block that is shown.

When .upload is clicked on, check currentBlock < maxBlock. If it is, increment the current block that should be shown and concatenate .upload_block with currentBlock to get the jquery selector.

var maxBlock = 5;
var currentBlock = 1;
$('.upload').click(function() {
    if(currentBlock < maxBlock) {
        currentBlock ++;
        $('.upload_block'  + currentBlock).show(0);
    }
});
Comments