jquerywordpressmenu

Making a smarter jQuery code applied to a Wordpress Menu


On my Wordpress menu I tagged a .custom-class-n on each links via the back-office. This gives a menu structure like this :

<ul>
  <li id="menu-item-227" class="custom-class-1 menu-item ..."></li>
  <li id="menu-item-228" class="custom-class-2 menu-item ..."></li>
  ...
  <li id="menu-item-n" class="custom-class-n menu-item ..."></li>
</ul>

For each .custom-class I have another list that mirrors like this :

<div>
  <p class="custom-class-1"></p>
  <p class="custom-class-2"></p>
  ...
  <p class="custom-class-n"></p>
</div>

The end result is : when I hover .custom-class-1 thenp.custom-class-1 reacts. For now, I managed it through jQuery via this code :

jQuery( document ).ready(function( $ ) {
$('li.custom-class-1').on("mouseenter", function () {
    $('p.custom-class-1').addClass("hover");
    }).on("mouseleave", function () {
    $('p.custom-class-1').removeClass("hover");
    }); });

It works fine, but I have to duplicate it for each instance which is big and not viable for the end user.

How do I make this code? So I don't have to copy-paste it for every .custom-class-n

Note that the .custom-class-n is always first in line in the wordpress structure.


Solution

  • You need to delegate - life gets easier if you use data attributes

    $(function() {
      $('li[id^="menu-item"]').on("mouseenter mouseleave", function(event) {
        $(`p.${this.dataset.target}`).toggleClass("hover", event.type === "mouseenter");
      });
    });
    p.hover {
      font-weight: bold;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <ul>
      <li id="menu-item-227" data-target="custom-class-1" class="menu-item">227</li>
      <li id="menu-item-228" data-target="custom-class-2" class="menu-item">228</li>
      <li id="menu-item-n" data-target="custom-class-n " class="menu-item">n</li>
    </ul>
    <div>
      <p class="custom-class-1">P 1 </p>
      <p class="custom-class-2">P 2</p>
      <p class="custom-class-n">P n</p>
    </div>