Reputation: 3
I am trying to show the data of the next class test. For example, when I hover on the second box it should show the third etc.
The problem is that the first box is inside the divs. Using next() and children() the second box shows the third but it does not work when hovering on the first box.
$('.box').hover(
function() {
var element = $(this).next().children();
text = element.attr('data');
$(this).append('<div id="boxText">' + text + '</div>');
},
function() {
$('#boxText').remove();
}
);
.test {
padding: 75px;
background: #eee;
float: left;
margin: 5px;
border: solid 1px #ddd;
cursor: pointer;
}
#boxText {
position: absolute;
bottom: -35px;
left: 5px;
width: 150px;
text-align: center;
background: #45719B;
color: #FFF;
border: solid 1px #26445F;
font-family: Arial, Helvetica, sans-serif;
padding: 5px 0;
}
.box {
position: relative;
float: left;
margin: 0;
padding: 0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<a class="box">
<span class="test" data="first"></span>
</a>
</div>
</div>
<a class="box">
<span class="test" data="second"></span>
</a>
<a class="box">
<span class="test" data="third"></span>
</a>
Upvotes: 0
Views: 35
Reputation: 24965
Something like this perhaps?
var $boxes = $('.box');
$boxes.hover(
function(){
var $hoveredBox = $(this);
//get the box at the index after our hovered index
var $nextBox = $boxes.eq($boxes.index($hoveredBox) + 1);
if ($nextBox.length) {
$hoveredBox.append('<div id="boxText">'+ $nextBox.find('.test').attr('data') +'</div>');
}
},
function(){
$('#boxText').remove();
}
);
.test{
padding:75px;
background:#eee;
float:left;
margin:5px;
border:solid 1px #ddd;
cursor:pointer;
}
#boxText{
position:absolute;
bottom:-35px;
left:5px;
width:150px;
text-align:center;
background:#45719B;
color:#FFF;
border:solid 1px #26445F;
font-family:Arial, Helvetica, sans-serif;
padding:5px 0;
}
.box{
position:relative;
float:left;
margin:0;
padding:0;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<div>
<a class="box">
<span class="test" data="first"></span>
</a>
</div>
</div>
<a class="box">
<span class="test" data="second"></span>
</a>
<a class="box">
<span class="test" data="third"></span>
</a>
Upvotes: 1