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?
How to disable HTML attributes with js?
43 Views Asked by Avarage cat enjoyer At
2
There are 2 best solutions below
1
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.
Try to prevent default action only on smaller screens.