0

I have three boxes across and one line of text below that changes the text based on which box is hovered over. HTML

<div style="display:inline-block;">
<div id="box1" class="outerbox">
</div>
<div id="box2" class="outerbox">
</div>
<div id="box3" class="outerbox">
</div>
</div>
<div style="display:block;">
  <p id="p1">
  Paragraph 1
  </p>
  <p id="p2">
  Paragraph 2
  </p>
  <p id="p3">
  Paragraph 3
  </p>
</div>

and I am running this script with it, which seems amateurishly repetitive.

$(document).ready(function() {
            $("#box1").hover(function() {
                $("#p1").addClass("show");
            }, function() {
                $("#p1").removeClass("show");
            });

      $("#box2").hover(function() {
                $("#p2").addClass("show");
            }, function() {
                $("#p2").removeClass("show");
            });

      $("#box3").hover(function() {
                $("#p3").addClass("show");
            }, function() {
                $("#p3").removeClass("show");
            });
        });

How would I better code the script to do the same function. Thanks. FIDDLE

2 Answers 2

2

Attach the event handler to the class, and give each box a data attribute that links it to the corresponding <p>.

$(document).ready(function() {
  $(".outerbox").hover(function() {
    $("#" + $(this).data('p')).addClass("show");
  }, function() {
    $("#" + $(this).data('p')).removeClass("show");
  });
});
#box1,
#box2,
#box3 {
  width: 100px;
  height: 100px;
  border: solid 2px #000;
  float: left;
  margin-right: 20px;
  position: relative;
  cursor: pointer;
}
p {
  display: none;
}
.show {
  display: block;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div style="display:inline-block;">
  <div id="box1" class="outerbox" data-p="p1">
  </div>
  <div id="box2" class="outerbox" data-p="p2">
  </div>
  <div id="box3" class="outerbox" data-p="p3">
  </div>
</div>
<div style="display:block;">
  <p id="p1">
    Paragraph 1
  </p>
  <p id="p2">
    Paragraph 2
  </p>
  <p id="p3">
    Paragraph 3
  </p>
</div>

Sign up to request clarification or add additional context in comments.

1 Comment

That was great help Barmar. Thank you very much for it.
0

Something like this:

 $(document).ready(function() {
        $(".outerbox").hover(function() {
            var getIndex = $(this).index();//Gets index of hovered elem
            //alert(getIndex);
            $("p").eq(getIndex).addClass("show");//Apply index of hovered elem to p elem
            }, function() {
            $("p").removeClass("show");
        });    
    });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.