JS: Should I use a switch-case statement or an if/else for this kind of situation?

I’m trying to minimize (make it more efficient) my JavaScript codes and debating which method I should approach.

I have 10+ pages where each page has two different videos; a short video shown for non-logged-in user and long video shown for logged-in user. I’m working on a WordPress website so I’m targeting each video using the post-id instead of the video player id(plugin) because it is dynamic (changes every time the page refresh). Each video on the page is wrapped in a class so I can target when either video has been clicked.

Read More

For example,

$f('#post-1883 .short-video .player').bind({
    ready : function(e) {
        e.preventDefault();
        console.log('short video'); 
        // Do something here if it's a short video      
    }   
});

 $f('#post-1883 .long-video .player').bind({
    ready : function(e) {
        e.preventDefault();
        console.log('long video');
        // Do something here if it's a long video           
    }   
}); 

As you can see in the example, it can be repetitive and clunky when you are targeting 10 videos in the JavaScript file with different post-ID (e.g. #post-1122, #post-4234, and so on).

What would be the best way to approach this situation? Should I use a switch-case statement?

Thanks,
rolu

Related posts

Leave a Reply

1 comment

  1. Is this works for you?

    $('.player').bind('click', function (e) {
        e.preventDefault();
        var self = $(this),
            videoId = this.id;
    
        if(self.hasClass('long-video')) {
            console.log('long video');
        } else if(self.hasClass('short-video')) {
            console.log('short-video');
            console.log(videoId);
        }
    });
    

    You can see the example working on: JsFiddle