Reputation: 1557
I am attempting to write a script which toggles pictures of videos however the switch seems to not work in my case and I'm terrible at javascript. I simply want on page load to set the vid=1;
and cycle through my options using the click events. Where did I go wrong? I am trying to use this example to use: switch statement in Jquery and List
My Code:
$(function(){
var vid=1;
$('#next-vid').click(function(){
switch (vid) {
case '1':
$('#vid1').hide();
$('#vid2').show();
$('#vid3').hide();
$('#vid4').hide();
vid=2;
break;
case '2':
$('#vid1').hide();
$('#vid2').hide();
$('#vid3').show();
$('#vid4').hide();
vid=3;
break;
case '3':
$('#vid1').hide();
$('#vid2').hide();
$('#vid3').hide();
$('#vid4').show();
vid=4;
break;
case '4':
$('#vid1').show();
$('#vid2').hide();
$('#vid3').hide();
$('#vid4').hide();
vid=1;
break;
}
});
$('#prev-vid').click(function(){
switch (vid) {
case '1':
$('#vid1').hide();
$('#vid2').hide();
$('#vid3').hide();
$('#vid4').show();
vid=4;
break;
case '2':
$('#vid1').show();
$('#vid2').hide();
$('#vid3').hide();
$('#vid4').hide();
vid=1;
break;
case '3':
$('#vid1').hide();
$('#vid2').show();
$('#vid3').hide();
$('#vid4').show();
vid=2;
break;
case '4':
$('#vid1').hide();
$('#vid2').hide();
$('#vid3').show();
$('#vid4').hide();
vid=3;
break;
}
});
});
Upvotes: 0
Views: 143
Reputation: 10407
The switch is unnecessary.
var vid=1;
$('#next-vid').click(function(){
vid = vid === 4 ? 1 : vid+1;
$('[id^="vid"]').hide();
$('#vid'+vid).show();
});
$('#prev-vid').click(function(){
vid = vid === 1 ? 4 : vid-1;
$('[id^="vid"]').hide();
$('#vid'+vid).show();
});
Upvotes: 1
Reputation: 324750
Erm... that could be a LOT simpler.
$(function() {
var vid = 0;
$("#next-vid").click(function() {
vid = (vid + 1) % 4;
$("[id^=vid]").hide();
$("#vid"+(vid+1)).show();
});
$("#prev-vid").click(function() {
vid = (vid + 3) % 4;
$("[id^=vid]").hide();
$("#vid"+(vid+1)).show();
});
});
Upvotes: 4