简体   繁体   中英

on hover event hide the div

I want to hide the div 'sample' on hover event and need to show the div 'sample' on mouseout

 $('.secmenu').hover(function() { $('.sample').css('opacity', '0'); if ($('.secmenu').mouseleave()) { $('.sample').css('opacity', '1'); } }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="" class="secmenu">click</a> <div class="sample"> hello div sample text content hello div sample text content </div> 

 $('.secmenu').mouseenter(function() {//hide div on mouse enter $('.sample').hide(); }).mouseleave(function() {//show div on mouse leave $('.sample').show(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="" class="secmenu">click</a> <div class="sample"> hello div sample text content hello div sample text content </div> 

This can be done in css. No need of jQuery:

 .secmenu:hover + .sample { display: none; } 
 <a href="" class="secmenu">click</a> <div class="sample"> hello div sample text content hello div sample text content </div> 

Hide div on hover and show div on mouseleave event. You need to bind the mouseleave event not write it in if condition.

$(document).ready(function () {

    $('.secmenu').hover(function () {

        $('.sample').css('opacity', '0');

    });
    $('.secmenu').mouseleave(function () {
        $('.sample').css('opacity', '1');
    });
});

Try this:

 $('.secmenu').on('mouseenter',function() { $('.sample').css('opacity', '0'); }).on('mouseleave',function(){ $('.sample').css('opacity', '1'); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <a href="" class="secmenu">click</a> <div class="sample"> hello div sample text content hello div sample text content </div> 

If .sample is immediate next sibling of .secmneu you don't need JavaScript or jQuery for this. You can do it with pure CSS.

 .sample { transition: opacity 0.25s ease; opacity: 0; } .secmenu:hover + .sample { opacity: 1; } 
 <a href="" class="secmenu">click</a> <div class="sample"> hello div sample text content hello div sample text content </div> 

According to jQuery's documentation :

Bind one or two handlers to the matched elements, to be executed when the mouse pointer enters and leaves the elements.

.hover( handlerIn, handlerOut )

So you can do it like this ( try it out ):

$( '.secmenu' ).hover(
  function() {
    $('.sample').hide();
  },
  function() {
    $('.sample').show();
  }
);

Which is equivalent to:

$( selector ).mouseenter( handlerIn ).mouseleave( handlerOut );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM