Javascript: notes on using switch

function whatClicked(x) {
//z=(x) //this line works
//clickResult=alert("you clicked " + z) //this line works
x=parseInt(x); // see the value passed as a number
switch (x)
{
case 1:
alert("you clicked 1");
break;
case 2:
alert("you clicked 2");
break;
case 3:
alert("you clicked 3");
break;
case 4:
alert("you clicked 4")
break;
default:
alert("oops");
}
}

To use the switch with the x value that is being set in the a tag, the switch statement must be used in the same code block of the function that finds the value of x. So, basically, contain the swtich within the function. Also, the x=parseInt(x) line makes the value from the a tag that was clicked and sees it as a number instead of a string. So, if you passed the string “1abc” from the onclick in the a tag to the whatClicked function, using parseInt() would use only the number from that string.

The alerts within the switch cases will be replaced with the functionality I originally meant. This is just for testing. Now that I know it works to this point, I will begin adding some jQuery to take the bigSquare and move it around and resize when the a tags are clicked.

$(document).ready(function() {
$('#content1').hide();
});

//var bigSquareOrigin=$('.bigSquare').animate({left:"40%", top:"40%"})

// get a value from the a tag that will replace x
function whatClicked(x) {
//z=(x) //this line works
//clickResult=alert("you clicked " + z) //this line works
x=parseInt(x);

// if that x value equals one of these cases, do something and stop.
switch (x)
{
case 1:
$('.bigSquare').animate({left:"0px", top:"0px"}, function(){
$('#content1').show("slow");
})

break;
case 2:
alert("you clicked 2");
break;
case 3:
alert("you clicked 3");
break;
case 4:
alert("you clicked 4")
break;
case 5:
$('#content1').hide("fast", function(){
$('.bigSquare').animate({left:"40%", top:"40%"});
});

break;
default:
alert("oops");
}
} // end of function whatClicked

So, I got everything working the way I want. But, in case 1 of the switch, the animation of the big square and the showing of the content were happening at the same time. I needed to separate the effects in order to achieve a result that moved the big square first, then proceeded to show the content box.

Luckily, there is a way. You simply type a comma after the last animate bracket and write a function that contains the second part of the case. So, for my desired effect, I simply moved the showing of the content box into an inner function and it suddenly behave exactly as I intended.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s