X
X
Xveeder2018-02-15 07:28:48
JavaScript
Xveeder, 2018-02-15 07:28:48

How do I change the style of only the hovered element in jQuery?

Hello, friends.

There is a code:

<div class="post-item">
                  <img src="img/1.jpg" alt="">
                  <div class="post-gradient"></div>
                  <div class="post-item_inner">
                      <h2><a href="#">Заголовок статьи</a></h2>
                      <div class="post-meta">
                         <div class="post-comment">
                             <i class="fa fa-commenting"></i>
                             <span class="comments-link">
                                <a href="#">5</a>
                             </span>
                         </div>
                         <div class="post-views">
                             <i class="fa fa-eye"></i>
                             <span class="comments-link">
                                <a href="#">2398</a>
                             </span>
                         </div>  
                      </div>
                  </div>
              </div>


It is necessary that when you hover over .post-item, the style of .post-gradient changes. I

wrote the following code and everything seems to work:

$('.post-item').hover(
                function(){
                    $('.post-gradient').css('background','linear-gradient(to top, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.2) 70%)');
                },
                function(){
                    $('.post-gradient').css('background','linear-gradient(to top, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.2) 70%)');
                }
            );


The problem is that on hover, ALL elements with the .post-gradient class change, and I need only the one I hover over to change. How to do it? Why not attach it to each id card and write 4 scripts?

Thank you.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Rsa97, 2018-02-15
@Xveeder

$('.post-item').hover(
  function() {
    $(this).children('.post-gradient').css('background','linear-gradient(to top, rgba(0, 0, 0, 0.8) 0%, rgba(0, 0, 0, 0.2) 70%)');
  },
  function() {
    $(this).children('.post-gradient').css('background','linear-gradient(to top, rgba(0, 0, 0, 0.5) 0%, rgba(0, 0, 0, 0.2) 70%)');
  }
);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question