Jquery on hover and out
Asked Answered
L

4

9

I am trying to hide a div whenever I will hover over it and show another one in the same place.. And when I take the mouse out of that.. the previous div will be shown and this div will be hidden...

$(document).ready(function(){



      $('#hover_tutor').hover(
         function () {
           $('#hover_tutor').hide();
           $('#hover_tutor_hidden').show();
         }, 
         function () {
           $('#hover_tutor').show();
         $('#hover_tutor_hidden').hide();
         }
     );

   });



  <div id="hover_tutor">Blah</div>
  <div id="hover_tutor_hidden" style="display:none;">Bleh</div>

But on hovering the hover_tutor... something is happening.. It's jumping up and down.. I don't know what's wrong...

Limousin answered 27/1, 2015 at 5:54 Comment(2)
why you add 2 function?Kristopherkristos
@RandykaYudhistira 2 functions is more or less what is needed, but attached to different classes` mouse eventsRachele
R
18

You need to use .mouseenter event for #hover_tutor div and .mouseleave for #hover_tutor_hidden div:

$('#hover_tutor').mouseenter(function () {
       $(this).hide();
       $('#hover_tutor_hidden').show();
     });

 $('#hover_tutor_hidden').mouseleave(function () {
       $('#hover_tutor').show();
     $(this).hide();
     }
 ).mouseleave();//trigger mouseleave to hide second div in beginning 

Working Demo

Revelation answered 27/1, 2015 at 5:56 Comment(1)
This could be revised with more explanation and be a featured answer. Excellent example.Tahiti
C
2

You can also use toggle method instent of hide/show on hover event

<div id="hover_tutor" style="display: block;">Blah</div>
<div id="hover_tutor_hidden" style="display: none;">Bleh</div>

  $('#hover_tutor').hover(
     function () {
      $('#hover_tutor').toggle();
       $('#hover_tutor_hidden').toggle();
     });

Working demo http://jsfiddle.net/ivyansh9897/8jgjvkqk/

Clareclarence answered 27/1, 2015 at 6:9 Comment(0)
P
1

If you do have the flexibility to modify your html little bit using class attribute there's a better way. Use .toggle() to alter the state of your element on both mouseover and mouseleave.

HTML :

<div id="hover_tutor" class="hello">Blah</div>
<div id="hover_tutor_hidden" class="hello" style="display:none;">Bleh</div>

jQuery :

$(".hello").on("mouseover mouseleave", function(){
    $("#hover_tutor").toggle();
    $("#hover_tutor_hidden").toggle();
});

jsFiddle

Pancratium answered 27/1, 2015 at 6:0 Comment(0)
S
1

try this,

$('#hover_tutor').hover(function () {
           $(this).hide();
           $('#hover_tutor_hidden').show();
         });

 $('#hover_tutor_hidden').hover(function () {
           $('#hover_tutor').show();
         $(this).hide();
         }
     ));
Skiing answered 27/1, 2015 at 6:7 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.