0

I tried this solution but am missing something: change background of parent div on hover

Here is my html:

<div class="box">
    <h3 class="page-header item-title">                                              
          <a class="titlelink" href="/index.php?option=com_content&amp;view=category&amp;id=11&amp;Itemid=234">
                Modeling</a>

This is what I tried to use in an override here: /templates/shaper_helixultimate/html/com_content/category/default_children.php

$document = JFactory::getDocument();
$document->addScriptDeclaration('
$('.box > .titlelink').hover(function(){
$(this).parent().toggleClass('hover');
})
    });
');

http://jsfiddle.net/t5hf8qdc/

What am I doing wrong?

$('.box > .titlelink').hover(function() {
  $(this).parent().toggleClass('hover');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="box">
  <h3 class="page-header item-title">
    <a class="titlelink" href="/index.php?option=com_content&amp;view=category&amp;id=11&amp;Itemid=234">
                    Modeling</a>
  </h3>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
modernmagic
  • 141
  • 10

2 Answers2

1

The selector .box > .titlelink looks for a parent-child relationship. You don't have that.

Use .box .titlelink instead.

$('.box .titlelink').hover(function() {
  $(this).parent().toggleClass('hover');
});
.hover {
  background: pink;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="box">
  <h3 class="page-header item-title">
    <a class="titlelink" href="/index.php?option=com_content&amp;view=category&amp;id=11&amp;Itemid=234">
                    Modeling</a>
  </h3>
</div>
isherwood
  • 58,414
  • 16
  • 114
  • 157
1

As @isherwood mentioned, the solution you linked to uses a different structure than what you have. The > in CSS selectors specifies that you're targeting a direct child, while just leaving a space between the two selectors looks for any descendant.

.box > .titlelink {
  /* targets where .titlelink is a child of .box */
}

.box .titlelink {
  /* targets where .titlelink is a descendant of .box */
}

If you want to use a strict CSS selector like the solution you referenced, you could do:

$('.box > .item-title > .titlelink').hover(function(){
  $(this).parent().toggleClass('hover');
});

Although this will add the hover class to the .item-title element, not to the .box element. Assuming that you specifically want target the .box ancestor of whatever you're listening for the hover event on, then you want:

$('.box > .item-title > .titlelink').hover(function(){
  $(this).parents('.box').toggleClass('hover');
});

since jQuery's parents method allows you to pass a selector to target a specific ancestor, travelling multiple levels up through the tree.