Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jquery how to change only one parent on hover

I would like to change only one parent when I hover over <p> tags. The code is:

$('.hover').each(function () {
    $(this).parent().hover(function () {
            $('p').parent(this).css('font-size','30px');
        }, function () {
            $('p').parent(this).css('font-size','10px');
    });
});

and the HTML is:

   <ul>
        <li>1 <p class='hover'>xxxx</p></li>
        <li>2 <p class='hover'>yyyy</p></li>
    </ul>

When I hover over "xxxx", I want "1" and "xxxx" to change but "2" and "yyyy" do nothing, and when I hover over "yyyy", I want "2" and "yyyy" to change but "1" and "xxxx" do nothing.

I'm new to jQuery.

like image 933
Choo Chu Avatar asked Sep 13 '12 12:09

Choo Chu


People also ask

How to apply CSS to child element based on parent in jQuery?

The task is to apply CSS property to a child element using jQuery. To do that, first we select the child element with the help of children() method in jQuery and then apply CSS property to it with the help of css() method in jQuery.

How can we prevent child element affected by parents hover state?

Basically you want to apply a negative scale on hover. so you apply the positive scale to the parent div and a negative scale to the child.


1 Answers

$('p.hover').parent().hover(function() {
    $(this).children('p').css('font-size','30px');
}, function () {
    $(this).children('p').css('font-size','10px');
});

You don't have to use an each loop to add the hovers. If you have multiple elements selected, it will apply the event on all elements.

Having that said, I slightly optimised your code.

I have added the hover on the paragraph's parent, just like you did. By using $(this) in the event's callback I can actually select the hovered element and apply styles on that element.

Because I want the font-size to apply on the paragraph, I select the desired child first.


Summing above up:

  • Find the paragraphs elements ($('p.hover'))
  • Get it's parent, the li element (.parent())
  • Apply the hover event (.hover())

Once the hover event is called:

  • Get current element ($(this))
  • Find the inner paragraph (.children('p'))
  • Apply styles
like image 99
Tim S. Avatar answered Oct 27 '22 19:10

Tim S.