1

I need a simple script that would alert me with index number of certain div within a div.

Hovering over first box gives it's index (0) then another gives 1,2,3 etc. Result I'm looking for is so third and fourth .box div would give their indexes within .box-container so 0 then 1 and not index of them within whole document. How would I approach such task? I know my code is close just not close enough.

$(".box").mouseover(function() {
  console.log($(".box").index($(this)));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box-container">
  <div class="box">0</div>
  <div class="box">1</div>
</div>

<div class="box-container">
  <div class="box">2</div>
  <div class="box">3</div>
</div>
marc_s
  • 704,970
  • 168
  • 1,303
  • 1,425
Greg Viv
  • 757
  • 6
  • 21

1 Answers1

1

You are searching .box class specific index() function to get index of element. There is issue due to its getting incremental ways index of element.

if you do using $this their index() it works.

Below is example :

$(".box").mouseover(function() {
  console.log($(this).index());
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box-container">
  <div class="box">0</div>
  <div class="box">1</div>
</div>

<div class="box-container">
  <div class="box">2</div>
  <div class="box">3</div>
</div>
aviboy2006
  • 7,334
  • 5
  • 24
  • 43
  • 1
    While this code may provide a solution to problem, it is highly recommended that you provide additional context regarding why and/or how this code answers the question. Code only answers typically become useless in the long-run because future viewers experiencing similar problems cannot understand the reasoning behind the solution. – palaѕн Jul 08 '20 at 14:37
  • Thanks for feedback. Added details. – aviboy2006 Jul 08 '20 at 14:38
  • The result I was looking for is 0,1,0,1 (cause boxes marked as 2 and 3 are in separate .box-container - and it's an index of them within that .box-container I need) – Greg Viv Jul 08 '20 at 14:47
  • It’s give index of element which is hover box class – aviboy2006 Jul 08 '20 at 14:59