1

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' : '';
      });
});
0

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

8 Comments

2nd argument of attr can be either a String or a function - I don't believe he's using it incorrectly.
@Tibrogargan but $(this) is not refering to the element with the attribute. In his case it is refering to $('body') which is wrong. I assumed he want to get the current value of the elements attribute. I could've mentioned that in my answer, yes.
The problem now, is that when you click one of the nav links, it sets the data-drawer-display to hide. Clicking the body shows the nav on click, but releasing the mouse hides the nav again.
@user3438917 I assume that's because nav is a child of body so the event is always firing. I'll update my answer
Hmm, this is still causing the nav to toggle on and off, when clicking on the links: $('body').on('click touchstart',function(e){ if ($(e.target).is('nav')) { return false; } $( ".nav-header" ).attr( "data-drawer-display", function( i, val ) { return val === 'show' ? 'hide' : 'show'; }); });
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.