jason328 jason328 - 5 months ago 25
Javascript Question

Toggling hover on dropdown between mobile and desktop

I have some simple JS that removes or adds html based on the width of the browser. If it's in mobile then the attribute

data-hover
should be removed. If the width is in desktop, then the attribute should be added.

So far this works great, but the problem is Bootstrap doesn't recognize that
data-hover
has been removed. The dropdown still closes when the user's mouse leaves the dropdown. To be clear, I want the dropdown to stay open when the user's mouse leaves the dropdown when the window browser width's is below 768px.

What's wrong and how do I fix this?

JS

$(document).ready(function () {
$( window ).resize(function() {
if ($( window ).width() < 768) {
$('.dropdown-toggle').removeAttr('data-hover');
} else {
$('.dropdown-toggle').attr('data-hover', 'dropdown');
}
});
});


HTML

<a class="dropdown-toggle" data-hover="dropdown" data-toggle="dropdown" role="menu" aria-expanded="false" href="/courses">
Courses
</a>

<ul class="dropdown-menu courses-dropdown">
<li>hello</li>
</ul>

BDD BDD
Answer

Instead of removing the attribute completely, you could reassign it to nothing like so:

$('.dropdown-toggle').attr('data-hover', '');

If there is no value assigned to the attribute, it shouldn't do anything.

Comments