WordPress links with hashes and disabling a links normal behavior

WordPress allows for the creation of custom links within the Menu’s area. I like this feature, it has been around for years.

I use it sometimes to create internal and external links but there are cases where I wanted them disabled. In this case and as you may have experienced – a custom link requires a value. It’s pretty common to just put a hash “#” as a value.

Something like href=”#”. This however will cause the element to behave normally as it should – there’s nothing wrong with that except it will cause your page to “jump” back up to the top of the page which can be annoying for visitors.

Below a snippet solution to take care of this. Jquery is still awesome, the $ sign is still awesome, despite the new kids on the block – vue.js, angular and friends.


<script>
$(document).ready(function(){

   $('#menu-top-nav li a[href^="#"]').click(function(e){
      e.preventDefault();
   });

});
</script>

We target the menu element and access any link containing hash. We pass the event object (a global environment object) and run it’s method preventDefault() to prevent the link from behaving like a link. And voila – done and done.