Carousel in Vanilla JavaScript The 2019 Stack Overflow Developer Survey Results Are InImage Carousel in JavaScriptInteractive sliderVanilla Javascript live filterVanilla Carousel: code above configurationVanilla JavaScript ToDo List implementationJavaScript/jQuery carousel/sliderVanilla JavaScript to-do listPopup classes hierarchy designJavascript image carouselVanilla JavaScript Calculator

writing variables above the numbers in tikz picture

Does HR tell a hiring manager about salary negotiations?

How to type this arrow in math mode?

What is the most efficient way to store a numeric range?

Accepted by European university, rejected by all American ones I applied to? Possible reasons?

The phrase "to the numbers born"?

Can there be female White Walkers?

How can I define good in a religion that claims no moral authority?

Finding the area between two curves with Integrate

Can withdrawing asylum be illegal?

How to notate time signature switching consistently every measure

Is an up-to-date browser secure on an out-of-date OS?

"as much details as you can remember"

How to type a long/em dash `—`

What is the meaning of Triage in Cybersec world?

Pokemon Turn Based battle (Python)

Did the UK government pay "millions and millions of dollars" to try to snag Julian Assange?

What do these terms in Caesar's Gallic Wars mean?

RequirePermission not working

Correct punctuation for showing a character's confusion

Geography at the pixel level

How do PCB vias affect signal quality?

Why isn't the circumferential light around the M87 black hole's event horizon symmetric?

Why couldn't they take pictures of a closer black hole?



Carousel in Vanilla JavaScript



The 2019 Stack Overflow Developer Survey Results Are InImage Carousel in JavaScriptInteractive sliderVanilla Javascript live filterVanilla Carousel: code above configurationVanilla JavaScript ToDo List implementationJavaScript/jQuery carousel/sliderVanilla JavaScript to-do listPopup classes hierarchy designJavascript image carouselVanilla JavaScript Calculator



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








4












$begingroup$


I finally got my carousel to work in JavaScript, and I want to know what you guys think about it and what I can do better.






var reviews = document.getElementsByClassName('review');
var leftArrow = document.getElementsByClassName('arrow')[0];
var rightArrow = document.getElementsByClassName('arrow')[1];

var currentReview;
var nextReview;

function carousel(direction)
for (var i = 0; i < reviews.length; i++)
if (reviews[i].classList.contains("show"))
currentReview = reviews[i];
if (direction == 'forward')
if (i + 1 > reviews.length - 1)
nextReview = reviews[0];
else
nextReview = reviews[i + 1];

else
if (i - 1 < 0)
nextReview = reviews[reviews.length - 1];
else
nextReview = reviews[i - 1];





currentReview.classList.remove("show");
nextReview.classList.add("show");


leftArrow.onclick = function()
carousel('backward');

rightArrow.onclick = function()
carousel('forward');

* 
font-family: Arial;


.carousel
display: flex;
align-items: center;
justify-content: center;


.review
display: none;
text-align: center;


.show
display: block;


.arrow
margin-left: 25vw;
margin-right: 25vw;


.arrow-left
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-right: 10px solid black;


.arrow-right
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid black;

<div class="carousel">
<div class="arrow-left arrow"></div>
<div class="reviews">
<div class="review show">
<h1 class="title">Title1</h1>
</div>
<div class="review">
<h1 class="title">Title2</h1>
</div>
<div class="review">
<h1 class="title">Title3</h1>
</div>
</div>
<div class="arrow-right arrow"></div>





JSFiddle










share|improve this question











$endgroup$




bumped to the homepage by Community 9 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.










  • 1




    $begingroup$
    @Iwrestledabearonce check - sorry, I didn't try the left button. Way to be! "Sometimes You Eat the Bear, and Sometimes the Bear Eats You."
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    Jan 9 '18 at 22:02










  • $begingroup$
    You are using the rather modern classList, but not e.g. the let keyword. What environments/browsers would you like to support?
    $endgroup$
    – Jeroen
    Jan 16 '18 at 23:17


















4












$begingroup$


I finally got my carousel to work in JavaScript, and I want to know what you guys think about it and what I can do better.






var reviews = document.getElementsByClassName('review');
var leftArrow = document.getElementsByClassName('arrow')[0];
var rightArrow = document.getElementsByClassName('arrow')[1];

var currentReview;
var nextReview;

function carousel(direction)
for (var i = 0; i < reviews.length; i++)
if (reviews[i].classList.contains("show"))
currentReview = reviews[i];
if (direction == 'forward')
if (i + 1 > reviews.length - 1)
nextReview = reviews[0];
else
nextReview = reviews[i + 1];

else
if (i - 1 < 0)
nextReview = reviews[reviews.length - 1];
else
nextReview = reviews[i - 1];





currentReview.classList.remove("show");
nextReview.classList.add("show");


leftArrow.onclick = function()
carousel('backward');

rightArrow.onclick = function()
carousel('forward');

* 
font-family: Arial;


.carousel
display: flex;
align-items: center;
justify-content: center;


.review
display: none;
text-align: center;


.show
display: block;


.arrow
margin-left: 25vw;
margin-right: 25vw;


.arrow-left
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-right: 10px solid black;


.arrow-right
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid black;

<div class="carousel">
<div class="arrow-left arrow"></div>
<div class="reviews">
<div class="review show">
<h1 class="title">Title1</h1>
</div>
<div class="review">
<h1 class="title">Title2</h1>
</div>
<div class="review">
<h1 class="title">Title3</h1>
</div>
</div>
<div class="arrow-right arrow"></div>





JSFiddle










share|improve this question











$endgroup$




bumped to the homepage by Community 9 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.










  • 1




    $begingroup$
    @Iwrestledabearonce check - sorry, I didn't try the left button. Way to be! "Sometimes You Eat the Bear, and Sometimes the Bear Eats You."
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    Jan 9 '18 at 22:02










  • $begingroup$
    You are using the rather modern classList, but not e.g. the let keyword. What environments/browsers would you like to support?
    $endgroup$
    – Jeroen
    Jan 16 '18 at 23:17














4












4








4





$begingroup$


I finally got my carousel to work in JavaScript, and I want to know what you guys think about it and what I can do better.






var reviews = document.getElementsByClassName('review');
var leftArrow = document.getElementsByClassName('arrow')[0];
var rightArrow = document.getElementsByClassName('arrow')[1];

var currentReview;
var nextReview;

function carousel(direction)
for (var i = 0; i < reviews.length; i++)
if (reviews[i].classList.contains("show"))
currentReview = reviews[i];
if (direction == 'forward')
if (i + 1 > reviews.length - 1)
nextReview = reviews[0];
else
nextReview = reviews[i + 1];

else
if (i - 1 < 0)
nextReview = reviews[reviews.length - 1];
else
nextReview = reviews[i - 1];





currentReview.classList.remove("show");
nextReview.classList.add("show");


leftArrow.onclick = function()
carousel('backward');

rightArrow.onclick = function()
carousel('forward');

* 
font-family: Arial;


.carousel
display: flex;
align-items: center;
justify-content: center;


.review
display: none;
text-align: center;


.show
display: block;


.arrow
margin-left: 25vw;
margin-right: 25vw;


.arrow-left
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-right: 10px solid black;


.arrow-right
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid black;

<div class="carousel">
<div class="arrow-left arrow"></div>
<div class="reviews">
<div class="review show">
<h1 class="title">Title1</h1>
</div>
<div class="review">
<h1 class="title">Title2</h1>
</div>
<div class="review">
<h1 class="title">Title3</h1>
</div>
</div>
<div class="arrow-right arrow"></div>





JSFiddle










share|improve this question











$endgroup$




I finally got my carousel to work in JavaScript, and I want to know what you guys think about it and what I can do better.






var reviews = document.getElementsByClassName('review');
var leftArrow = document.getElementsByClassName('arrow')[0];
var rightArrow = document.getElementsByClassName('arrow')[1];

var currentReview;
var nextReview;

function carousel(direction)
for (var i = 0; i < reviews.length; i++)
if (reviews[i].classList.contains("show"))
currentReview = reviews[i];
if (direction == 'forward')
if (i + 1 > reviews.length - 1)
nextReview = reviews[0];
else
nextReview = reviews[i + 1];

else
if (i - 1 < 0)
nextReview = reviews[reviews.length - 1];
else
nextReview = reviews[i - 1];





currentReview.classList.remove("show");
nextReview.classList.add("show");


leftArrow.onclick = function()
carousel('backward');

rightArrow.onclick = function()
carousel('forward');

* 
font-family: Arial;


.carousel
display: flex;
align-items: center;
justify-content: center;


.review
display: none;
text-align: center;


.show
display: block;


.arrow
margin-left: 25vw;
margin-right: 25vw;


.arrow-left
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-right: 10px solid black;


.arrow-right
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid black;

<div class="carousel">
<div class="arrow-left arrow"></div>
<div class="reviews">
<div class="review show">
<h1 class="title">Title1</h1>
</div>
<div class="review">
<h1 class="title">Title2</h1>
</div>
<div class="review">
<h1 class="title">Title3</h1>
</div>
</div>
<div class="arrow-right arrow"></div>





JSFiddle






var reviews = document.getElementsByClassName('review');
var leftArrow = document.getElementsByClassName('arrow')[0];
var rightArrow = document.getElementsByClassName('arrow')[1];

var currentReview;
var nextReview;

function carousel(direction)
for (var i = 0; i < reviews.length; i++)
if (reviews[i].classList.contains("show"))
currentReview = reviews[i];
if (direction == 'forward')
if (i + 1 > reviews.length - 1)
nextReview = reviews[0];
else
nextReview = reviews[i + 1];

else
if (i - 1 < 0)
nextReview = reviews[reviews.length - 1];
else
nextReview = reviews[i - 1];





currentReview.classList.remove("show");
nextReview.classList.add("show");


leftArrow.onclick = function()
carousel('backward');

rightArrow.onclick = function()
carousel('forward');

* 
font-family: Arial;


.carousel
display: flex;
align-items: center;
justify-content: center;


.review
display: none;
text-align: center;


.show
display: block;


.arrow
margin-left: 25vw;
margin-right: 25vw;


.arrow-left
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-right: 10px solid black;


.arrow-right
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid black;

<div class="carousel">
<div class="arrow-left arrow"></div>
<div class="reviews">
<div class="review show">
<h1 class="title">Title1</h1>
</div>
<div class="review">
<h1 class="title">Title2</h1>
</div>
<div class="review">
<h1 class="title">Title3</h1>
</div>
</div>
<div class="arrow-right arrow"></div>





var reviews = document.getElementsByClassName('review');
var leftArrow = document.getElementsByClassName('arrow')[0];
var rightArrow = document.getElementsByClassName('arrow')[1];

var currentReview;
var nextReview;

function carousel(direction)
for (var i = 0; i < reviews.length; i++)
if (reviews[i].classList.contains("show"))
currentReview = reviews[i];
if (direction == 'forward')
if (i + 1 > reviews.length - 1)
nextReview = reviews[0];
else
nextReview = reviews[i + 1];

else
if (i - 1 < 0)
nextReview = reviews[reviews.length - 1];
else
nextReview = reviews[i - 1];





currentReview.classList.remove("show");
nextReview.classList.add("show");


leftArrow.onclick = function()
carousel('backward');

rightArrow.onclick = function()
carousel('forward');

* 
font-family: Arial;


.carousel
display: flex;
align-items: center;
justify-content: center;


.review
display: none;
text-align: center;


.show
display: block;


.arrow
margin-left: 25vw;
margin-right: 25vw;


.arrow-left
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-right: 10px solid black;


.arrow-right
width: 0;
height: 0;
border-top: 10px solid transparent;
border-bottom: 10px solid transparent;
border-left: 10px solid black;

<div class="carousel">
<div class="arrow-left arrow"></div>
<div class="reviews">
<div class="review show">
<h1 class="title">Title1</h1>
</div>
<div class="review">
<h1 class="title">Title2</h1>
</div>
<div class="review">
<h1 class="title">Title3</h1>
</div>
</div>
<div class="arrow-right arrow"></div>






javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jan 9 '18 at 21:34









iwrestledabearonce

2,032613




2,032613










asked Jan 9 '18 at 20:02









Jordan BaronJordan Baron

1264




1264





bumped to the homepage by Community 9 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.







bumped to the homepage by Community 9 mins ago


This question has answers that may be good or bad; the system has marked it active so that they can be reviewed.









  • 1




    $begingroup$
    @Iwrestledabearonce check - sorry, I didn't try the left button. Way to be! "Sometimes You Eat the Bear, and Sometimes the Bear Eats You."
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    Jan 9 '18 at 22:02










  • $begingroup$
    You are using the rather modern classList, but not e.g. the let keyword. What environments/browsers would you like to support?
    $endgroup$
    – Jeroen
    Jan 16 '18 at 23:17













  • 1




    $begingroup$
    @Iwrestledabearonce check - sorry, I didn't try the left button. Way to be! "Sometimes You Eat the Bear, and Sometimes the Bear Eats You."
    $endgroup$
    – Sᴀᴍ Onᴇᴌᴀ
    Jan 9 '18 at 22:02










  • $begingroup$
    You are using the rather modern classList, but not e.g. the let keyword. What environments/browsers would you like to support?
    $endgroup$
    – Jeroen
    Jan 16 '18 at 23:17








1




1




$begingroup$
@Iwrestledabearonce check - sorry, I didn't try the left button. Way to be! "Sometimes You Eat the Bear, and Sometimes the Bear Eats You."
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
Jan 9 '18 at 22:02




$begingroup$
@Iwrestledabearonce check - sorry, I didn't try the left button. Way to be! "Sometimes You Eat the Bear, and Sometimes the Bear Eats You."
$endgroup$
– Sᴀᴍ Onᴇᴌᴀ
Jan 9 '18 at 22:02












$begingroup$
You are using the rather modern classList, but not e.g. the let keyword. What environments/browsers would you like to support?
$endgroup$
– Jeroen
Jan 16 '18 at 23:17





$begingroup$
You are using the rather modern classList, but not e.g. the let keyword. What environments/browsers would you like to support?
$endgroup$
– Jeroen
Jan 16 '18 at 23:17











1 Answer
1






active

oldest

votes


















0












$begingroup$

Put space around control structures & label some closing braces, IMO if > 2 consecutive closing braces then start labeling - about every 3rd one.



for (var i = 0; i < reviews.length; i++) {

if (reviews[i].classList.contains("show"))
currentReview = reviews[i];

if (direction == 'forward')

if (i + 1 > reviews.length - 1)
nextReview = reviews[0];
else
nextReview = reviews[i + 1];


else

if (i - 1 < 0)
nextReview = reviews[reviews.length - 1];
else
nextReview = reviews[i - 1];


// if direction





Logic nesting is too much. When I read that final else Im saying "else what? Where am I?" Too many ifs is bad enough, with if/else code clarity is out the window and bug potential explodes.



for (var i = 0; i < reviews.length; i++) 

switch(direction)
case 'forward':
// your code here
break;

case 'backward' :
// your code here
break;

default :
alert(`direction "$direction" is invalid`);
// switch



switch goodness:



  • encourages use of a default. Get in the habit of writing error trapping.

  • Your code is "forward, or anything not forward" -> in contrast this is "forward", "backward", "anything else is a mistake".

  • Explicitly coding for all conditions unambiguously tells the reader what's what.

  • Extensible. Adding another condition is easy. In contract the nested if/else is very highly error prone. And you can imagine that switch complexity does not compound like if/else.

  • All the above makes it an ideal place for your general dispatching.


Given separate event handlers code can be simpler because a parameter is not required and code is greatly simplified. The for loop is unnecessary. Note that currentReview, nextReview are now indexes, not the objects themselves - which actually means only one of these is needed. There may be some redundant code for showing & hiding but the simplicity is very compelling.



function forward() 
nextReview = currentReview >= classList.length - 1? 0 : ++currentReview;
// reviews[nextReview] ....


function backward()
nextReview = currentReview <= 0 ? classList.length - 1 : --currentReview;
// you know what to do here






share|improve this answer











$endgroup$













    Your Answer





    StackExchange.ifUsing("editor", function ()
    return StackExchange.using("mathjaxEditing", function ()
    StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix)
    StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
    );
    );
    , "mathjax-editing");

    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "196"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f184681%2fcarousel-in-vanilla-javascript%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0












    $begingroup$

    Put space around control structures & label some closing braces, IMO if > 2 consecutive closing braces then start labeling - about every 3rd one.



    for (var i = 0; i < reviews.length; i++) {

    if (reviews[i].classList.contains("show"))
    currentReview = reviews[i];

    if (direction == 'forward')

    if (i + 1 > reviews.length - 1)
    nextReview = reviews[0];
    else
    nextReview = reviews[i + 1];


    else

    if (i - 1 < 0)
    nextReview = reviews[reviews.length - 1];
    else
    nextReview = reviews[i - 1];


    // if direction





    Logic nesting is too much. When I read that final else Im saying "else what? Where am I?" Too many ifs is bad enough, with if/else code clarity is out the window and bug potential explodes.



    for (var i = 0; i < reviews.length; i++) 

    switch(direction)
    case 'forward':
    // your code here
    break;

    case 'backward' :
    // your code here
    break;

    default :
    alert(`direction "$direction" is invalid`);
    // switch



    switch goodness:



    • encourages use of a default. Get in the habit of writing error trapping.

    • Your code is "forward, or anything not forward" -> in contrast this is "forward", "backward", "anything else is a mistake".

    • Explicitly coding for all conditions unambiguously tells the reader what's what.

    • Extensible. Adding another condition is easy. In contract the nested if/else is very highly error prone. And you can imagine that switch complexity does not compound like if/else.

    • All the above makes it an ideal place for your general dispatching.


    Given separate event handlers code can be simpler because a parameter is not required and code is greatly simplified. The for loop is unnecessary. Note that currentReview, nextReview are now indexes, not the objects themselves - which actually means only one of these is needed. There may be some redundant code for showing & hiding but the simplicity is very compelling.



    function forward() 
    nextReview = currentReview >= classList.length - 1? 0 : ++currentReview;
    // reviews[nextReview] ....


    function backward()
    nextReview = currentReview <= 0 ? classList.length - 1 : --currentReview;
    // you know what to do here






    share|improve this answer











    $endgroup$

















      0












      $begingroup$

      Put space around control structures & label some closing braces, IMO if > 2 consecutive closing braces then start labeling - about every 3rd one.



      for (var i = 0; i < reviews.length; i++) {

      if (reviews[i].classList.contains("show"))
      currentReview = reviews[i];

      if (direction == 'forward')

      if (i + 1 > reviews.length - 1)
      nextReview = reviews[0];
      else
      nextReview = reviews[i + 1];


      else

      if (i - 1 < 0)
      nextReview = reviews[reviews.length - 1];
      else
      nextReview = reviews[i - 1];


      // if direction





      Logic nesting is too much. When I read that final else Im saying "else what? Where am I?" Too many ifs is bad enough, with if/else code clarity is out the window and bug potential explodes.



      for (var i = 0; i < reviews.length; i++) 

      switch(direction)
      case 'forward':
      // your code here
      break;

      case 'backward' :
      // your code here
      break;

      default :
      alert(`direction "$direction" is invalid`);
      // switch



      switch goodness:



      • encourages use of a default. Get in the habit of writing error trapping.

      • Your code is "forward, or anything not forward" -> in contrast this is "forward", "backward", "anything else is a mistake".

      • Explicitly coding for all conditions unambiguously tells the reader what's what.

      • Extensible. Adding another condition is easy. In contract the nested if/else is very highly error prone. And you can imagine that switch complexity does not compound like if/else.

      • All the above makes it an ideal place for your general dispatching.


      Given separate event handlers code can be simpler because a parameter is not required and code is greatly simplified. The for loop is unnecessary. Note that currentReview, nextReview are now indexes, not the objects themselves - which actually means only one of these is needed. There may be some redundant code for showing & hiding but the simplicity is very compelling.



      function forward() 
      nextReview = currentReview >= classList.length - 1? 0 : ++currentReview;
      // reviews[nextReview] ....


      function backward()
      nextReview = currentReview <= 0 ? classList.length - 1 : --currentReview;
      // you know what to do here






      share|improve this answer











      $endgroup$















        0












        0








        0





        $begingroup$

        Put space around control structures & label some closing braces, IMO if > 2 consecutive closing braces then start labeling - about every 3rd one.



        for (var i = 0; i < reviews.length; i++) {

        if (reviews[i].classList.contains("show"))
        currentReview = reviews[i];

        if (direction == 'forward')

        if (i + 1 > reviews.length - 1)
        nextReview = reviews[0];
        else
        nextReview = reviews[i + 1];


        else

        if (i - 1 < 0)
        nextReview = reviews[reviews.length - 1];
        else
        nextReview = reviews[i - 1];


        // if direction





        Logic nesting is too much. When I read that final else Im saying "else what? Where am I?" Too many ifs is bad enough, with if/else code clarity is out the window and bug potential explodes.



        for (var i = 0; i < reviews.length; i++) 

        switch(direction)
        case 'forward':
        // your code here
        break;

        case 'backward' :
        // your code here
        break;

        default :
        alert(`direction "$direction" is invalid`);
        // switch



        switch goodness:



        • encourages use of a default. Get in the habit of writing error trapping.

        • Your code is "forward, or anything not forward" -> in contrast this is "forward", "backward", "anything else is a mistake".

        • Explicitly coding for all conditions unambiguously tells the reader what's what.

        • Extensible. Adding another condition is easy. In contract the nested if/else is very highly error prone. And you can imagine that switch complexity does not compound like if/else.

        • All the above makes it an ideal place for your general dispatching.


        Given separate event handlers code can be simpler because a parameter is not required and code is greatly simplified. The for loop is unnecessary. Note that currentReview, nextReview are now indexes, not the objects themselves - which actually means only one of these is needed. There may be some redundant code for showing & hiding but the simplicity is very compelling.



        function forward() 
        nextReview = currentReview >= classList.length - 1? 0 : ++currentReview;
        // reviews[nextReview] ....


        function backward()
        nextReview = currentReview <= 0 ? classList.length - 1 : --currentReview;
        // you know what to do here






        share|improve this answer











        $endgroup$



        Put space around control structures & label some closing braces, IMO if > 2 consecutive closing braces then start labeling - about every 3rd one.



        for (var i = 0; i < reviews.length; i++) {

        if (reviews[i].classList.contains("show"))
        currentReview = reviews[i];

        if (direction == 'forward')

        if (i + 1 > reviews.length - 1)
        nextReview = reviews[0];
        else
        nextReview = reviews[i + 1];


        else

        if (i - 1 < 0)
        nextReview = reviews[reviews.length - 1];
        else
        nextReview = reviews[i - 1];


        // if direction





        Logic nesting is too much. When I read that final else Im saying "else what? Where am I?" Too many ifs is bad enough, with if/else code clarity is out the window and bug potential explodes.



        for (var i = 0; i < reviews.length; i++) 

        switch(direction)
        case 'forward':
        // your code here
        break;

        case 'backward' :
        // your code here
        break;

        default :
        alert(`direction "$direction" is invalid`);
        // switch



        switch goodness:



        • encourages use of a default. Get in the habit of writing error trapping.

        • Your code is "forward, or anything not forward" -> in contrast this is "forward", "backward", "anything else is a mistake".

        • Explicitly coding for all conditions unambiguously tells the reader what's what.

        • Extensible. Adding another condition is easy. In contract the nested if/else is very highly error prone. And you can imagine that switch complexity does not compound like if/else.

        • All the above makes it an ideal place for your general dispatching.


        Given separate event handlers code can be simpler because a parameter is not required and code is greatly simplified. The for loop is unnecessary. Note that currentReview, nextReview are now indexes, not the objects themselves - which actually means only one of these is needed. There may be some redundant code for showing & hiding but the simplicity is very compelling.



        function forward() 
        nextReview = currentReview >= classList.length - 1? 0 : ++currentReview;
        // reviews[nextReview] ....


        function backward()
        nextReview = currentReview <= 0 ? classList.length - 1 : --currentReview;
        // you know what to do here







        share|improve this answer














        share|improve this answer



        share|improve this answer








        edited Jan 16 '18 at 21:57

























        answered Jan 16 '18 at 21:47









        radarbobradarbob

        5,4701127




        5,4701127



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Code Review Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            Use MathJax to format equations. MathJax reference.


            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f184681%2fcarousel-in-vanilla-javascript%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            名間水力發電廠 目录 沿革 設施 鄰近設施 註釋 外部連結 导航菜单23°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.7113923°50′10″N 120°42′41″E / 23.83611°N 120.71139°E / 23.83611; 120.71139計畫概要原始内容臺灣第一座BOT 模式開發的水力發電廠-名間水力電廠名間水力發電廠 水利署首件BOT案原始内容《小檔案》名間電廠 首座BOT水力發電廠原始内容名間電廠BOT - 經濟部水利署中區水資源局

            Prove that NP is closed under karp reduction?Space(n) not closed under Karp reductions - what about NTime(n)?Class P is closed under rotation?Prove or disprove that $NL$ is closed under polynomial many-one reductions$mathbfNC_2$ is closed under log-space reductionOn Karp reductionwhen can I know if a class (complexity) is closed under reduction (cook/karp)Check if class $PSPACE$ is closed under polyonomially space reductionIs NPSPACE also closed under polynomial-time reduction and under log-space reduction?Prove PSPACE is closed under complement?Prove PSPACE is closed under union?

            Is my guitar’s action too high? Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 23, 2019 at 23:30 UTC (7:30pm US/Eastern)Strings too stiff on a recently purchased acoustic guitar | Cort AD880CEIs the action of my guitar really high?Μy little finger is too weak to play guitarWith guitar, how long should I give my fingers to strengthen / callous?When playing a fret the guitar sounds mutedPlaying (Barre) chords up the guitar neckI think my guitar strings are wound too tight and I can't play barre chordsF barre chord on an SG guitarHow to find to the right strings of a barre chord by feel?High action on higher fret on my steel acoustic guitar