Home > Mobile >  JQuery Hover Method - Out function is not working
JQuery Hover Method - Out function is not working

Time:12-28

I am applying an hover effect on an image with JQuery.

State on page load :

On Page Load

State on hover :

State on Hover

State on mouseout :

State on Hover

Here is the code snippet :

$(document).ready(function(){
    $(".image-container").hover(function() {
    $(this).parents().children().children('.image-01').css({'background-color':'#D4E619', 'opacity': '0.5'}),
   
 (function() {
    $(this).parents().children().children('.image-01').css({'background-color':'#FFFFF','height':'0', 'opacity': '0', 'visibility' :'hidden'});
    });
});
});

I tried several css instructions but the image keeps the hover state.

Edit :

The final goal is to have a different hover color on several images inside a grid. All elements of the grid have the same classname.

I use a first JQuery function to append the classnames and then, generates a specific hover state on some images.

CodePudding user response:

It's because you mixed in and out functions into single one. So your second function that (I assume) should be called on mouse out is never called.

You should unwrap that function from first one and put as second argument for .hover

$(document).ready(function() {
  $(".image-container").hover(
    function() {
      $(this).parents().children().children('.image-01').css({
        'background-color': '#D4E619',
        'opacity': '0.5'
      })
    },
    function() {
      $(this).parents().children().children('.image-01').css({
        'background-color': '#FFFFF',
        'height': '0',
        'opacity': '0',
        'visibility': 'hidden'
      });
    }
  );
});


Some suggestions (quite abstract since no HTML is provided):

  1. You can reduce complexity of selector by finding closest unique wrapper and then find desired element: $(this).closes('.image-wrapper').find('.image-01')
  2. Via JS apply only display/opacity. Via CSS set rules for element when it's shown, no point in setting it's background if it's not visible: $(this).[..].show(), $(this).[..].hide()
  3. I assume you can just do it with css: .image-wrapper:hover .image-01{display: block;}

CodePudding user response:

Suggestions:

  1. Use id for the image, so you can reduce dom complexity.
  2. Use two separate events (.hover and .mouseout)
  3. Use arrow functions rather than 'function' keyword

Example:

$(document).ready(()=>{
    $("#image-01").hover(()=>{
        /* css code for hover here */
    }
    $("#image-01").mouseout(()=>{
        /* css code for mouseout here */
    }
}

Edit:

  1. Maybe you can warp all of your images in a div element.
    Then you can use

    let images = $(' /* container id */ ').children()

    To get its children.

    Then just loop through the images and add hover events

  • Related