Pergunta

I have blocks of information displayed in divs. I want to change the css of a particular div on hover. But currently when I hover over anyone div the css for all the divs change.

Here's my jquery code :-

<script>
        $('.student-box').hover( function(){
            $('.student-info').css('opacity', '0.8');
            $('.student-info').css('margin-top', '-20px');
            $('.student-info').css('height', '130%');
            $('.onhover-ul').show();
        },
        function(){
            $('.student-info').css('opacity', '0.7');
            $('.student-info').css('margin-top', '75px');
            $('.student-info').css('height', '63%');
            $('.onhover-ul').hide();
        });
    </script> 

How do I change the jquery so that only the div which is hovered upon is affected. There can be a lot of student which means lot of "student-box" will be generated.

Foi útil?

Solução 2

Try this:

$('.student-box').hover( function(){
    var div = $(this);

    div.find('.student-info').css({
         opacity: '0.8'
         marginTop: '-20px',
         height: '130%'
    });
    div.find('.onhover-ul').show();
}, function(){
    var div = $(this);

    div.find('.student-info').css({
        opacity: '0.7',
        marginTop: '75px',
        height: '63%'
    });
    div.find('.onhover-ul').hide();
});

It doesn't matter that you called the hover() method on a div, inside the callback you're still just saying 'select all elements with the class ...'

Inside the callback function, this is the DOM element that actually triggered the event. So you can wrap this in jQuery and call methods on it.

Using the css() method in this way though isn't advised, you're better off adding a class name and moving the styling to a style sheet, otherwise you've got presentation in your behaviour.

Outras dicas

$('.student-box').hover( function(){       
       // $(this) is DOM element what hovered at this moment

       $(this).find('.student-info').css({
          'opacity': '0.8',
          'margin-top', '-20px',
          'height', '130%'
       });
   },
   function(){
         // unhover code like hover
   })
);
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top