I am creating an submenu that expands when clicked on the anchor tag or the svg. I have used a javascript to achieve this. The problem I’m facing is, only either of them is working at a time. I tried wrapping them in single divs and added new classes to target the elements but there is no success. I even tried the querySelectorAll to target both of them at once but still there was an error. How do I achieve this? I am attaching part of my code below. The below code if the very basic approach. If needed I can share code where I have used wrapper.
const searchb = document.querySelector("b1000");
const subMenu = document.getElementById("nav2-seachex");
searchb.addEventListener("click", function() {
subMenu.style.right = "0";
});
subMenu.addEventListener("click", function(event) {
event.stopPropagation();
});
#nav2-seachex {
position: fixed;
top: 0;
left: -700px;
width: 100%;
max-width: 1300px;
height: 100%;
background-color: rgb(247, 3, 3);
z-index: 999;
}
.nav2-search svg {
width: 24px;
height: 24px;
cursor: pointer;
}
<div class="nav2-search">
<a class="b1000" href="">search</a>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256">
<rect width="256" height="256" fill="none"/>
<circle cx="116" cy="116" r="84" fill="none" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="14"/>
<line x1="175.4" y1="175.4" x2="224" y2="224" fill="none" stroke="#000" stroke-linecap="round" stroke-linejoin="round" stroke-width="14"/>
</svg>
</div>
<div id="nav2-seachex">
<a href="">x</a>
</div>
2
Answers
You can simplify your code by wrapping the
<svg>
icon in a button – so you only need one event listener for the button.Besides, prefer
<button>
over<a>
elements if you need to trigger some action instead of an actual link/anchor jump. This way you also don’t need to disable default link behavior viapreventDefault()
.Here’s a common approach for a nav toggle functionality – based on class toggling/replacements.