0

I have some very simple code to get information about active div with class name active. I currently trying to get its index between a collection of divs with class name slide. However, I tried many selectors with no benefit. So, I need your help.

CSS

<style type="text/css">

.slide {
    width:50px;border:1px solid #808080;height:50px;float:left; display:inline-block;
    text-align:center; vertical-align:middle;/*display:none;*/
}
.active { background-color:brown }
</style>

HTML

<div style="text-align:center">
    <input id="get_info" type="button" value="<<>>" /> 

    <br />
        <div style="display:inline-block">
            <div class="slide ">0</div>
            <div class="slide">1</div>
            <div class="slide active">2</div>
            <div class="slide">3</div>
        </div>
    <br />
    <p id="msg"></p>
</div>

jQuery:

<script type="text/javascript">
    $(document).ready(function () {
        var nxt = 0;
        var prv = 0;
        var crnt = 0;

        $("#get_info").click(function () {
            crnt = $(".slide").index(".slide .active");
            $('#msg').html(crnt);
        });

    });
</script>

As shown all I need to get "active" position index between "slide". The permanent result for this is -1.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

1 Answers1

0

You can get it like this:

$(document).ready(function() {   
  $("#get_info").click(function() {
    let crnt = $(".slide").index($(".slide.active"));
    $('#msg').html(crnt);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div style="text-align:center">
    <input id="get_info" type="button" value="<<>>" /> 

    <br />
        <div style="display:inline-block">
            <div class="slide ">0</div>
            <div class="slide">1</div>
            <div class="slide active">2</div>
            <div class="slide">3</div>
        </div>
    <br />
    <p id="msg"></p>
</div>
matthias_h
  • 11,356
  • 9
  • 22
  • 40
  • Would you please explain or add a reference to what is "let". Thanks for your answer. –  May 02 '20 at 10:56
  • 1
    @MOHAMEDABUELATTA In short, let is another option to declare a variable instead of using var. Full explanation e.g. here: https://stackoverflow.com/questions/762011/whats-the-difference-between-using-let-and-var – matthias_h May 02 '20 at 10:59
  • @MOHAMEDABUELATTA And for a reference check https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let – matthias_h May 02 '20 at 11:09