Reputation: 1216
I am trying to add an image caption to a div, the code below works fine and does what I want, however I would like to ask your advise to make the code a bit shorter :) I believe that there is a better way to do so, but I couldn't find it.
Thanks in advance.
HTML
<div id="firstBlock" class="block"><p class="caption c1">Description</p></div>
<div id="secondBlock" class="block"><p class="caption c2">Description</p></div>
<div id="thirdBlock" class="block"><p class="caption c3">Description</p></div>
<div id="fourthBlock" class="block"><p class="caption c4">Description</p></div>
JQuery
$("#firstBlock").hover(
function(){
$(".caption.c1").animate({"margin-left": "0px"});
},
function(){
$(".caption.c1").animate({"margin-left": "-200px"});
}
);
$("#secondBlock").hover(
function(){
$(".caption.c2").animate({"margin-left": "0px"});
},
function(){
$(".caption.c2").animate({"margin-left": "-200px"});
}
);
$("#thirdBlock").hover(
function(){
$(".caption.c3").animate({"margin-left": "0px"});
},
function(){
$(".caption.c3").animate({"margin-left": "-200px"});
}
);
$("#fourthBlock").hover(
function(){
$(".caption.c4").animate({"margin-left": "0px"});
},
function(){
$(".caption.c4").animate({"margin-left": "-200px"});
}
);
CSS
.caption{
height: 150px;
width: 200px;
text-align: center;
margin-left: -200px;
margin-top: 350px;
background: black;
color: white;
}
Upvotes: 1
Views: 426
Reputation: 4572
You can clean your JavaScript code. For example:
$('.block').hover(function() {
$(this).find('.caption').animate({
"margin-left": "0px"
});
}, function() {
$(this).find('.caption').animate({
"margin-left": "-200px",
});
});
Upvotes: 1
Reputation: 28387
No need to use separate classes. Use the common class and then find the caption.
$(".block").hover(
function () {
$(this).find(".caption").animate({
"margin-left": "0px"
});
},
function () {
$(this).find(".caption").animate({
"margin-left": "-200px"
});
}
);
Upvotes: 1