Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Hiding and showing the text only when it is necessary with jquery

I have a link and some text. Whenever I hover over the link the text should be displayed with a time interval of 1200 secs and should be hidden immediately when I remove the cursor from the link. So, according to what I have written, whenever I hover over the link the text is getting displayed after 1200 secs and after the text got displayed when I remove the cursor from the link the text is getting hidden which is fine. but whenever I keep the cursor on the link and remove the cursor from the link before the text is getting displayed, the text is still being shown, which I don't want to be shown. The text should be hidden immediately when I remove the cursor from the link.

Is there any way to do that. I have provided the code that I have written below: Please take a look at it, Thanks in advance :)

$('a').hover(function(){
    setTimeout(function(){
    $('.show-hide').css("visibility", "visible")}, 1200);
}, 
function(){
     $('.show-hide').css("visibility", "hidden");
});
.show-hide{
  visibility : hidden;
  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#"><p> Hover here </p></a>


<p class="show-hide"> This should be shown when hovered </p>

<p class="show-hide"> This should be shown when hovered </p>
like image 257
Harish Avatar asked Jan 04 '23 20:01

Harish


1 Answers

It is happening because the show() function executes when you hover over it and even when you leave the mouse before 1.2 seconds, you are not preventing it, it will show the text once the delay is completed.

You need to execute hide() when mouseleave. that way it will stop the show() function. Try the snippet below:

$(document).ready(function(){
  $('.show-hide').hide();
  //This is for showing the text with delay 1.2 sec
  $('a').mouseenter(function(){
    $('.show-hide').show(1200);
  });
  //This is for hiding the text with no delay
  $('a').mouseleave(function(){
    $('.show-hide').hide();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#"><p>Hover here</p></a>

<p class="show-hide"> This should be shown when hovered </p>
<p class="show-hide"> This should be shown when hovered </p>
like image 63
ab29007 Avatar answered Jan 08 '23 05:01

ab29007