How to change the style of a parent <li> when hovering over a child element

To change the style of a parent <li> when hovering over a child element, you can use JavaScript or jQuery to achieve this effect.

Here’s an example using jQuery:

  1. Make sure you have jQuery properly enqueued in your WordPress theme. If you don’t know how to do that, refer to the previous tutorial on including jQuery in a WordPress theme.
  2. Create a custom JavaScript file, for example, custom-hover.js, in your theme’s /js/ directory.
  3. Add the following code to your custom-hover.js file:
(function($) {
    $(document).ready(function() {
        $('li').on('mouseenter', function() {
            $(this).css('background-color', 'red'); // Change the style as needed
        }).on('mouseleave', function() {
            $(this).css('background-color', ''); // Reset the style
        });
    });
})(jQuery);

This code will change the background color of the parent <li> element when hovering over any child element within the <li> element.

You can replace the css() method with any style change you want to apply.

  1. Enqueue your custom script in your theme. Add the following code to your theme’s functions.php file:
function my_theme_enqueue_scripts() {
    wp_enqueue_script('my-custom-hover-script', get_template_directory_uri() . '/js/custom-hover.js', array('jquery'), '1.0', true);
}
add_action('wp_enqueue_scripts', 'my_theme_enqueue_scripts');

Replace /js/custom-hover.js with the path to your custom JavaScript file if you named it differently.

  1. Save the changes and refresh your website to see the effect.

Now, when you hover over a child element within an <li> element, the parent <li> element’s style will change as specified in the custom-hover.js file.

Remember to always backup your files before making any changes, and test your changes on a staging site or local development environment before applying them to your live site.

Leave a Reply

Your email address will not be published. Required fields are marked *