I have some very illogical jQuery code and I want to see if someone finds a better way to do the exact same thing:
jQuery:
$(".col-md-3 img").hover(function() {
$(this).parent().children(".search").show();
$(this).parent().children(".photo").css("opacity","0.4");
}, function(){
$(this).parent().children(".search").hide();
$(this).parent().children(".photo").css("opacity","1");
});
html {
background-color: #3498db;
}
.photo {
width:100%;
height: auto;
margin: 20px 0px;
}
.search {
position: absolute;
margin-left: auto;
margin-right: auto;
top:40%;
left: 0;
right: 0;
display: none;
}
.search:hover{
cursor:pointer;
}
<div class="col-md-3">
<img class="photo" src="http://florin-pop.com/work/Photo%20Gallery/img/1_small.jpg" alt="img" />
<img class="search hidden-xs" src="http://florin-pop.com/work/Photo%20Gallery/img/search.png" width="50px"/>
</div>
<!-- snippet jquery include -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
I have multiple similar divs.
I don't like the fact that I am accessing the DOM many times with:
$(this).parent().children();
I'm going back and forth and I think it might be a better solution.
The problem with the siblings() method is that one image is on top of the other image, with position absolute and this causes some tricky hover issues. The live website here: live
2 Answers 2
Semantic markup
The search.png
image is an artifact of the presentation; it isn't really part of the content. Therefore, it should not be written in the HTML.
Too much jQuery
This hover effect can be achieved using just CSS, and therefore it should be done in pure CSS.
html {
background-color: #3498db;
}
.col-md-3 {
width: 25%;
}
.photo {
position: relative;
width: 100%;
margin: 20px 0px;
}
.photo img {
width: 100%;
}
.photo:hover img {
opacity: 0.4;
}
.photo:hover::after {
position: absolute;
top: 0%;
left: 0;
right: 0;
bottom: 0;
background: url(http://florin-pop.com/work/Photo%20Gallery/img/search.png) 50% 50% no-repeat;
background-size: 50px 50px;
content: '';
cursor: pointer;
}
<div class="col-md-3">
<div class="photo"><img src="http://florin-pop.com/work/Photo%20Gallery/img/1_small.jpg" alt="" /></div>
</div>
I've used full URLs and background-image scaling for this demo. For your real site, you should use relative URLs and a pre-scaled magnifying glass image.
Instead of
$(this).parent().children(".search").show();
you can use
$(this).siblings(".search").show();
$(".search").show()
etc without the whole$(this).parent().children(...)
thing? Or, are there other elements of that class that you do not wan't accessed at that time? \$\endgroup\$