-1

I am trying to append a custom element on click on parent menu items to child menu items. When I click to parent item the code adds the custom Element. But when I click on an empty space of children item (CUSTOM ELEMENT) after custom element added, it keeps appending the elements.

$("li:has(ul)").click(function(e) {
    e.preventDefault();

    $("ul", this).animate({
        width: "40%"
    }, 200);
    
    var ele = '<h4 class="m-level-2" style="color: #d4dce5; text-transform: uppercase;font-family: Rajdhani,sans-serif;font-weight: 700;font-size: 1.875rem;margin-bottom: 0.5rem;">Altron<h4><h2 class="h4" style="color: #52c3df;text-transform: uppercase;font-family: Rajdhani,sans-serif;font-weight: 700;font-size: 3.75rem;margin-bottom: 1rem;"></h2><a href="#" class="nav-menu-back" style="color: #fff;font-size: 1rem;font-family: Montserrat,sans-serif;text-transform: none;">Go Back</a><hr style="background-color: #d4dce5; margin: 1.875rem 0;opacity: 1;height: 1px;" class="menu-hr">';
    $("ul", this).prepend(ele);
    let text = $(this).find("a").first().text();
    //console.log(text);
    $("ul", this).find("h2").text(text); 
});
Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Muhammad Shahid
  • 325
  • 1
  • 4
  • 12
  • I don't see a [custom element](https://developers.google.com/web/fundamentals/web-components/customelements) in your code. Can you help me find it? – connexo Jan 22 '22 at 17:28

1 Answers1

0

Clicking a child element will trigger a click handler on the parent. You can check if the click originated from your target element by checking e.currentTarget. Try this:


$("li:has(ul)").click(function(e) {
    e.preventDefault();
    if(e.target !== e.currentTarget){
      return;
    }

    $("ul", this).animate({
        width: "40%"
    }, 200);
    
    var ele = '<h4 class="m-level-2" style="color: #d4dce5; text-transform: uppercase;font-family: Rajdhani,sans-serif;font-weight: 700;font-size: 1.875rem;margin-bottom: 0.5rem;">Altron<h4><h2 class="h4" style="color: #52c3df;text-transform: uppercase;font-family: Rajdhani,sans-serif;font-weight: 700;font-size: 3.75rem;margin-bottom: 1rem;"></h2><a href="#" class="nav-menu-back" style="color: #fff;font-size: 1rem;font-family: Montserrat,sans-serif;text-transform: none;">Go Back</a><hr style="background-color: #d4dce5; margin: 1.875rem 0;opacity: 1;height: 1px;" class="menu-hr">';
    $("ul", this).prepend(ele);
    let text = $(this).find("a").first().text();
    //console.log(text);
    $("ul", this).find("h2").text(text); 
});

This answer explains currentTarget vs target: What is the exact difference between currentTarget property and target property in JavaScript

aclave1
  • 1,680
  • 18
  • 29