Building a JQUERY menu based on HOVER. When users mouse over ID TYPO it extracts the number of the TYPO ID and pass it to the ID of CAT. So if I hover DIV ID = TYPO2 it should display DIV ID=CAT2. This works fine except that I want to hide the CAT when mouse leaves and it doesn't work unless I declare again and repeat the catId variable in HOVER OUT. IS there another more efficient way the to this ?
Thanks in advance
CODE :
<script>
$(document).ready(function() {
$("#cat1, #cat2, #cat3").hide();
$("#typo1, #typo2, #typo3").hover(function(){
var catId = $(this).attr('id');
catId = catId.substring(4,5);
$("#cat"+catId).show("fast")
},
function(){
var catId = $(this).attr('i开发者_如何转开发d');
catId = catId.substring(4,5);
$("#cat"+catId).hide("fast")
});
});
</script>
<div id="container">
<div id="typo">
<div id="typo1" class="typo">Typo1</div>
<div id="typo2" class="typo">Typo2</div>
<div id="typo3" class="typo">Typo3</div>
</div>
<div class="clear"></div>
<div id="cat">
<div id="cat1">CAT1</div>
<div id="cat2">CAT2</div>
<div id="cat3">CAT3</div>
</div>
</div>
If you use classes and data-attributes it makes things much easier:
<script>
$(document).ready(function() {
$(".cat").hide();
$(".typo").hover(function(){
var catId = $(this).data('id');
$(".cat[data-id='"+catId+"']").show("fast")
},
function(){
var catId = $(this).data('id');
$(".cat[data-id='"+catId+"']").hide("fast")
});
});
</script>
<div id="container">
<div id="typo">
<div data-id="1" class="typo">Typo1</div>
<div data-id="2" class="typo">Typo2</div>
<div data-id="3" class="typo">Typo3</div>
</div>
<div class="clear"></div>
<div id="cat">
<div data-id="1" class="cat">CAT1</div>
<div data-id="2" class="cat">CAT2</div>
<div data-id="3" class="cat">CAT3</div>
</div>
</div>
You can also get rid of the IDs altogether now (if not needed).
精彩评论