patternjavascriptMinor
Showing different icons on hover
Viewed 0 times
differenticonsshowinghover
Problem
I have 30 icons, and after hover, different icons are shown. How can I write this shorter?
jQuery
HTML
jQuery
$('#iconTech01').hover(
function() {
$('#iconTechBig01').stop(true, true).fadeIn("slow");
$('#iconTech01 img').stop(true, true).fadeOut("slow");
},
function() {
$('#iconTechBig01').stop(true, true).fadeOut("slow");
$('#iconTech01 img').stop(true, true).fadeIn("slow");
});
$('#iconTech02').hover(
function() {
$('#iconTechBig02').stop(true, true).fadeIn("slow");
$('#iconTech02 img').stop(true, true).fadeOut("slow");
},
function() {
$('#iconTechBig02').stop(true, true).fadeOut("slow");
$('#iconTech02 img').stop(true, true).fadeIn("slow");
});
$('#iconTech03').hover(
function() {
$('#iconTechBig03').stop(true, true).fadeIn("slow");
$('#iconTech03 img').stop(true, true).fadeOut("slow");
},
function() {
$('#iconTechBig03').stop(true, true).fadeOut("slow");
$('#iconTech03 img').stop(true, true).fadeIn("slow");
});
$('#iconTech04').hover(
function() {
$('#iconTechBig04').stop(true, true).fadeIn("slow");
$('#iconTech04 img').stop(true, true).fadeOut("slow");
},
function() {
$('#iconTechBig04').stop(true, true).fadeOut("slow");
$('#iconTech04 img').stop(true, true).fadeIn("slow");
});
$('#iconTech05').hover(
function() {
$('#iconTechBig05').stop(true, true).fadeIn("slow");
$('#iconTech05 img').stop(true, true).fadeOut("slow");
},
function() {
$('#iconTechBig05').stop(true, true).fadeOut("slow");
$('#iconTech05 img').stop(true, true).fadeIn("slow");
});HTML
Solution
Certainly, assign a class to each tech icon (I'm assuming they're divs), use a JQuery selector to select all DOM element with the assigned class and then use
each() to step through each item.
$('.icon').each(function () {
$(this).hover(
function () {
$(this).stop(true, true).fadeIn("slow");
},
function () {
$('img', this).stop(true, true).fadeOut("slow");
}
);
});
Code Snippets
<div class="icon" id="iconTech01"><img ..../></div>
<div class="icon" id="iconTech02"><img ..../></div>
<div class="icon" id="iconTech03"><img ..../></div>
<script type="text/javascript">
$('.icon').each(function () {
$(this).hover(
function () {
$(this).stop(true, true).fadeIn("slow");
},
function () {
$('img', this).stop(true, true).fadeOut("slow");
}
);
});
</script>Context
StackExchange Code Review Q#12141, answer score: 4
Revisions (0)
No revisions yet.