How to disable HTML attributes with js?

43 views Asked by At

I have a menu with hover dropdown menus. On mobile I want to disable the href attribute so that clicking the link doesn't redirect, but opens the dropdown. I am currently using removeAttribute() to do that. But the problem is that if the user uses the site in a smaller window which triggers the mobile version and then makes the window bigger I need to add back the href. I could use setAttribute() but then I have to keep track of the links to add them back and I don't feel like that's the best solution. Is there a way to just disable the href attribute with js?

2

There are 2 answers

0
vitjbr On BEST ANSWER

Try to prevent default action only on smaller screens.

document.addEventListener('DOMContentLoaded', function() {
    var menuLink = document.getElementById('dropdownMenuLink'); // The menu link ID

    menuLink.addEventListener('click', function(event) {
        // Check if the viewport width is less than or equal to 768px (Adjust to your use case)
        if (window.innerWidth <= 768) {
            // Prevent default link action
            event.preventDefault();
            // Display an alert
            alert('Dropdown opening...'); // Placeholder action
            // Here you would toggle your dropdown or execute any other mobile-specific action
        }
        // On larger screens, the default action (navigation) proceeds
    });
});
<a href="#" class="menu-link" id="dropdownMenuLink">Menu Link</a>

1
passThru On

You can monitor for a screen resize with this event...

window.visualViewport.onresize=function(e){

 // And set conditions based on its height and/or width like this...

 if(this.offsetWidth < 800){                // Or use offsetHeight.

   a.href='javascript:SomeFunction();';     // If small make the href call a JS function.

 } else {

   a.href='https://somesite.com/';         // If big make it redirect to some url.

 }

};

NB: a.href is just a pseudo-code example… in real life you’ll have to specify which anchor by ID or some other way.