Hydra IO
Hydra IO

Reputation: 1557

Javascript / jQuery switch statement using static defined variable

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

Answers (2)

Adam Merrifield
Adam Merrifield

Reputation: 10407

The switch is unnecessary.

http://jsfiddle.net/MNe57/1/

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

Niet the Dark Absol
Niet the Dark Absol

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

Related Questions