user3438917 user3438917 - 4 months ago 29
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
data-drawer-display=""
. 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
show
to
hide
. 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.

SOLUTION

A modified version of @empiric below:

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

Answer

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.


Example

Edit

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

if ($(e.target).is('nav')) {
    return false;
}

Example 2