I have read it is a good practice to use the data- attribute to trigger CSS changes. I have this menu I want to build, and I want to change some CSS when the user clicks on a button.
I have some CSS rules set to open and closed, which I want to toggle depending on the data-attribute. I am setting the a data-atrib to data-navtogle on a dom node.
<div class="collapsing-navigation" data-navtoggle="closed">
I select that DOM node and change its value from closed to open.
menuMobile.navtoggle = 'open';
But it stays the same in the DOM, however if I call the attribute in the console it says it is open.
console.log('current attr is ='+ menuMobile.navtoggle); //current attr is open
In the console it says its open but in the DOMit says it still closed.
HTML
<nav class="navigation">
<div class="navigation-header">Header
<button type="button" class="menu-toggle">
<span class="sr-only">Toggle navigation</span>
<span class="hamburger-menu"></span>
<span class="hamburger-menu"></span>
<span class="hamburger-menu"></span>
</button>
</div>
<div class="collapsing-navigation" data-navtoggle="closed">
<ul>
<li class=""><a href="#">Home</a></li>
<li class=""><a href="#">About</a></li>
<li class="">
<a href="#">Solutions</a>
<ul>
<li class=""><a href="#">Sub 1</a></li>
<li class=""><a href="#">Sub 2</a></li>
<li class=""><a href="#">Sub 3</a></li>
</ul>
</li>
<li class=""><a href="#">Mobile</a></li>
<li class=""><a href="#">News</a></li>
<li class=""><a href="#">Contact</a></li>
</ul>
</div>
</nav>
Javascript:
$(function(){
var menuToggle = $('.menu-toggle');
var menuMobile = $('.collapsing-navigation');
menuToggle.on('click',function(){
if( menuMobile.data('navtoggle')==='closed' ){
console.log("it was closed and im setting it to open");
menuMobile.navtoggle = 'open';
console.log('current attr is ='+ menuMobile.navtoggle);
}
});
});
CSS:
.collapsing-navigation[data-navtoggle=closed]
height: 0
.collapsing-navigation[data-navtoggle=open]
height: 100vh
.collapsing-navigation
background-color: #00F
height: 100vh
position: relative
z-index: 10