I have a simple main navigation menu created with html and css. When I added some javascript to handle the collapsing and toggling for the button for the mobile menu, every link on the page stops working.
I based the navigation off of this pen: https://codepen.io/anon/pen/YQjzzq
(function() {
// Definition of caller element
var getTriggerElement = function(el) {
var isCollapse = el.getAttribute('data-collapse');
if (isCollapse !== null) {
return el;
} else {
var isParentCollapse = el.parentNode.getAttribute('data-collapse');
return (isParentCollapse !== null) ? el.parentNode : undefined;
}
};
// A handler for click on toggle button
var collapseClickHandler = function(event) {
var triggerEl = getTriggerElement(event.target);
// If trigger element does not exist
if (triggerEl === undefined) {
event.preventDefault();
return false;
}
// If the target element exists
var targetEl = document.querySelector(triggerEl.getAttribute('data-target'));
if (targetEl) {
triggerEl.classList.toggle('-active');
targetEl.classList.toggle('-on');
}
};
// Delegated event
document.addEventListener('click', collapseClickHandler, false);
})(document, window);
<nav role="navigation" id="navigation" class="list">
<a href="http://sitename.se/site/index.html" class="item -link">Hem</a>
<a href="http://sitename.se/site/vart-boende.html" class="item -link">Vårt Boende</a>
<a href="http://sitename.se/site/om-vald.html" class="item -link">Om Kvinnovåld</a>
<a href="http://sitename.se/site/lankar.html" class="item -link">Länkar</a>
<a href="http://sitename.se/site/engagera-dig.html" class="item -link">Engagera Dig</a>
<a href="http://sitename.se/site/english.html" class="item -link">English</a>
<a href="http://sitename.se/site/kontakt.html" class="item -link">Kontakt</a>
</nav>
<!-- Button to toggle the display menu -->
<button data-collapse data-target="#navigation" class="toggle">
<!-- Hamburger icon -->
<span class="icon"></span>
</button>
Currently, the links are not working because they are having their default behavior prevented on line 19 on the JavaScript. If I'm understanding the situation correctly, you only want the event listener to apply to the collapsible menu, so I'd suggest altering the code to something like this:
// Delegated event
document.getElementsByClassName('toggle')[0].addEventListener('click', collapseClickHandler, false);