Mouse over the image display text and disappear with the image (vice versa)

0

I'm trying to make this effect with the mouse over the image, it adds and displays the text, when you take the mouse, add the text and display the image.

I tried the following way, when I move the mouse over the image, it will be in "Infinite Loop" disappearing with the image and displaying the text (vice versa).

$(".agendamento li img").hover(function() {
  $(this).next("p").show();
  $(this).hide();
}, function() {
  $(this).next("p").hide();
  $(this).show();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="col-md-12 agendamento">
  <ul>
    <li class="col-md-12">
      <div class="col-md-6 borda-azul">
        <img src="http://placehold.it/350x150"alt="Terapia" class="img-responsive img-circle">
        <p>Proin eget tortor risus. Lorem ipsum dolor sit amet, consectetur adipiscing.</p>
      </div>
    </li>
  </ul>
</div>
    
asked by anonymous 28.04.2017 / 03:45

1 answer

1
The loop infinite happens because when you do $(this).hide() , the image is removed from the DOM, so the mouse is no longer on the element , firing the event handlerOut of hover . However, when this event is triggered, the image will be rendered again and the mouse will be on the image again, restarting the process.

To work around this problem, just work with the hover event of the parent element, in this case the div . When the mouse is over the element, the image disappears and the text appears, but when the mouse exits, the text disappears and the image reappears.

$(".agendamento li div").hover(function() {
  $(this).children("p").show();
  $(this).children("img").hide();
}, function() {
  $(this).children("p").hide();
  $(this).children("img").show();
});
ul {
  list-style: none;
}

.agendamento .borda-azul {
  width: 350px;
  height: 150px;
  border: 1px solid blue;
}

.agendamento li p {
  padding: 20px;
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><divclass="col-md-12 agendamento">
  <ul>
    <li class="col-md-12">
      <div class="col-md-6 borda-azul">
        <img src="http://placehold.it/350x150"alt="Terapia" class="img-responsive img-circle">
        <p>Proin eget tortor risus. Lorem ipsum dolor sit amet, consectetur adipiscing.</p>
      </div>
    </li>
  </ul>
</div>
  

Some CSS styles have been added to make the result more enjoyable, but they are not essential to the operation of the solution presented.

    
28.04.2017 / 04:04