I have a button with toggle class attached to it - and it should work only when the borwser size is below 1200px. It works after refresh but somehow when I resize the window it sometimes works and sometimes doesn't - can't see the pattern. I see on the dev tools the the element is higlighted (so hte script is doing something) but I doesn't toggle the class. Tried to change it to addClass/removeClass but the result is the same. Any advice how to make it work would be much appreciated.
CodePen: http://codepen.io/miunik/pen/oLWOLY
HTML:
<ul class="level-1">
<li class="btn">1 level item
<ul class="level-2">
<li>2 level item</li>
<li>2 level item</li>
<li>2 level item</li>
<li>2 level item</li>
</ul>
</li>
</ul>
CSS
ul.level-2 {
display: none;
}
ul.level-2.open {
display: block;
}
jQuery:
$(document).ready(function() {
function setNav() {
if (window.outerWidth < 1200) {
$('.btn').on({
click: function() {
$(this).children('.level-2').toggleClass('open');
}
});
}
}
setNav()
$(window).resize(function() {
setNav();
console.log(window.outerWidth);
});
});