user3438917 user3438917 - 1 year ago 58
jQuery Question

Toggle data attribute of nav with jquery

I have a nav header with a data attribute

<nav class="nav-header" data-drawer-display="show" data-drawer-num="0">

that sets the display of the navigation to either show or hide on click of a nav link, with
. I need to be able to toggle the navigation away by clicking on the body of the page with

$("body").on("click", function(){});

that should toggle the value from
. I have tried this:

$('body').on('click touchstart',function(e){
$( ".nav-header" ).attr( "data-drawer-display", function( i, val ) {
return val === 'show'?'hide':'show';

but the logic seems to be off.


A modified version of @empiric below:

$('body').on('touchstart', function(e){
//keeps nav from closing when clicking in subnav and links
if ($('.opener, .nav-sub, a')) {
return false;
//if subnav is open, close on body click.
$( ".nav-header" ).attr( "data-drawer-display", function( i, val ) {
return val === 'show' ? 'hide' : '';

Answer Source

You are using the callback of the attr()-function the wrong way.

Your $(this) will not refer to the element $('.nav-header'). In the function scope it is refering to $('body') which does not have an attribute data-drawer-display.

$( ".nav-header" ).attr( "data-drawer-display", function( i, val ) {
  return val === 'show'?'hide':'show';

should be working for you.



to avoid closing the nav when clicking on it (through event propagation) you can check for the clicked element:

if ($('nav')) {
    return false;

Example 2