allaspaniel allaspaniel - 7 months ago 18
HTML Question

Reduce code for hover for multiply element

How can I reduce this jQuery code without changing the HTML markup?
Should I use data- attributes?
But I have no idea how I can to come at this image element.
Here is example: https://jsfiddle.net/y277bavo/2/

$(".tlh-1, .tlb-1").hover(
function() {
$(".icon1-hover").css('display', 'block');
},
function() {
$(".icon1-hover").css('display', 'none');
});
$(".tlh-2, .tlb-2").hover(
function() {
$(".icon2-hover").css('display', 'block');
},
function() {
$(".icon2-hover").css('display', 'none');
});




<div class="row">
<div class="block">
<div class="head tlh-1">
<h4>Lorem ipsum.</h4>
</div>
<div class="body tlb-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed, facilis!.</div>
</div>
<p class="image-hover"><img class="icon1-hover" src="https://i.stack.imgur.com/F65tu.jpg?s=48&g=1" alt=""></p>
</div>
<div class="row">
<div class="block">
<div class="head tlh-2">
<h4>Lorem ipsum.</h4>
</div>
<div class="body tlb-2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed, facilis!.</div>
</div>
<p class="image-hover"><img class="icon2-hover" src="https://i.stack.imgur.com/F65tu.jpg?s=48&g=1" alt=""></p>
</div>

Answer

You can use DOM element relationship as

$(".block").hover(function() {
    $(this).closest('.row').find('.image-hover img').show();
},
function() {
    $(this).closest('.row').find('.image-hover img').hide();
});

$(".block").hover(function() {
    $(this).closest('.row').find('.image-hover img').show();
  },
  function() {
    $(this).closest('.row').find('.image-hover img').hide();
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="row">
  <div class="block">
    <div class="head tlh-1">
      <h4>Lorem ipsum.</h4>
    </div>
    <div class="body tlb-1">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed, facilis!.</div>
  </div>
  <p class="image-hover">
    <img class="icon1-hover" src="https://i.stack.imgur.com/F65tu.jpg?s=48&g=1" alt="">
  </p>
</div>
<div class="row">
  <div class="block">
    <div class="head tlh-2">
      <h4>Lorem ipsum.</h4>
    </div>
    <div class="body tlb-2">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Sed, facilis!.</div>
  </div>
  <p class="image-hover">
    <img class="icon2-hover" src="https://i.stack.imgur.com/F65tu.jpg?s=48&g=1" alt="">
  </p>
</div>