Home > Blockchain >  How to use prev/next for a group of div elements
How to use prev/next for a group of div elements

Time:05-09

So im trynna make a whole group of elements go next and frouth , off a code I took here but I edited it

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>     
<div >
    <div >
        <div>Yes 1 </div>
        <div>Element 1 </div>
    </div>
    <div >
        <div>Yes 1 </div>
        <div>Element 1 </div>
    </div>
    <div >
        <div>Yes 1 </div>
        <div>Element 1 </div>
    </div>

</div>
<a id="next">next</a>
<a id="prev">prev</a>
<script>
    $(document).ready(function(){
    $(".divs div").each(function(e) {
        if (e != 0)
            $(this).hide();
    });
    
    $("#next").click(function(){
        if ($(".divs div:visible").next().length != 0)
            $(".divs div:visible").next().show().prev().hide();
        else {
            $(".divs div:visible").hide();
            $(".divs div:first").show();
        }
        return false;
    });

    $("#prev").click(function(){
        if ($(".divs div:visible").prev().length != 0)
            $(".divs div:visible").prev().show().next().hide();
        else {
            $(".divs div:visible").hide();
            $(".divs div:last").show();
        }
        return false;
    });
});

</script>
</html>

When I click next , nothing shows up.And when I spam it random elements show up separately, I was the both elements to show up when I click next.

CodePudding user response:

  1. if you didn't use classes, use something like ".divs>div" to pinpoint the element if not the children would be included on the selection.

  2. It's just my preferences but if you code, one line is okay if the meaning is clear, but for this one it seems wasteful and not clear in a glance. It's also better to assign to variable than searching multiple times.

<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>     
<div >
    <div >
        <div>Yes 1 </div>
        <div>Element 1 </div>
    </div>
    <div >
        <div>Yes 2 </div>
        <div>Element 2 </div>
    </div>
    <div >
        <div>Yes 3 </div>
        <div>Element 3 </div>
    </div>

</div>
<a id="next">next</a>
<a id="prev">prev</a>
<script>
    $(document).ready(function(){
    $(".divs>div").each(function(e) {
        if (e != 0)
          $(this).hide();
    });
    
    $("#next").click(function(){
      const visibleDiv = $(".divs>div:visible");
      const nextDiv = visibleDiv.next();
      if(nextDiv.length > 0) {
        visibleDiv.hide();
        nextDiv.show();
      }

    });

    $("#prev").click(function(){
      const visibleDiv = $(".divs>div:visible");
      const prevDiv = visibleDiv.prev();
      if(prevDiv.length > 0) {
        visibleDiv.hide();
        prevDiv.show();
      }
    });
});

</script>
</html>

  • Related