Trying to get my navbar to close when I click off it?

This is the first time I’m doing anything with javvascript. I currently have this code for my website:


<title>My Website</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link href="navbar.css" rel="stylesheet" type="text/css" />

<body class="menu">
<a href="#" class="menu-toggle"><img src="" onmouseover="this.src=''" onmouseout="this.src=''" /></a>
<nav class="menu-side">
This is a side menu

<br />

<center>Content here

<script src=""></script>
(function() {
           var body = $('body');
           $('.menu-toggle').bind('click', function() {
                return false;


.menu {
    position: relative;
    left: 0px;

.menu-open {
    left: 231px;


.menu-open .menu-side {
    left: 0;

.menu {
    -webkit-transition: left 0.2s ease;
    -moz-transition: left 0.2s ease;
    transition: left 0.2s ease;


.menu-side {
    border-right:1px solid #000;
    top: 0;
    left: -231px;
    width: 210px;
    height: 100%;
    padding: 10px;


What can I do so that I don’t need to re-click the menu icon but can simply click off the navbar to close it?

Thank you!


Your jQuery code is not the best, try in this way

jQuery( function ($) {
  $('.menu-toggle').click( function() {
  } );
} );

Oh sorry seems like it’s okay, but this thing make something wrong

<a href="#" class="menu-toggle"><img src="" onmouseover="this.src=''" onmouseout="this.src=''" /></a>

The way this is usually handled is by registering a click event on the body and checking if you’ve clicked on something outside of the menu. This works because all events propagate up the DOM to the root node <html> unless they’re explicitly stopped.

var $body = $('body');
$body.on('click', function(event) {
  var clickedOutside = $('.menu-toggle').length == 0;
  if (clickedOutside && $body.hasClass('menu-open')) {

I disagree, the only thing I’d suggest changing in the original code is to use ‘on’ rather than bind for events, that’s the recommended method to use.

1 Like


Yes, it’s possible to move this outside of the HTML. It’s not too bad inline here but generally it’s great advice to keep your JS out of the HTML entirely.

$('.menu-toggle img').hover(function(event) {
  this.src = '';
}, function(event) {

Thank you very much Mark!

That worked a charm :slight_smile:

One thing that’s happened though. When I click on the nav bar or outside the nav bar, it closes it. I just want it to close if it’s clicked outside the nav bar, not inside as well. Any ideas? Thank you again!

That’s what this code was there to prevent, but you probably want to use .menu-side

var clickedOutside = $('.menu-side').length == 0;

Thank you again Mark, Life saver!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.