Reputation: 65
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
Upvotes: 0
Views: 69
Reputation: 2126
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");
});
});
Upvotes: 0
Reputation: 780949
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>
Upvotes: 2