2

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

html:

<head>
<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" />
</head>

<body class="menu">
<header>
<a href="#" class="menu-toggle"><img src="http://i.imgur.com/p2Yxaex.jpg" onmouseover="this.src='http://i.imgur.com/Vrl4tBl.jpg'" onmouseout="this.src='http://i.imgur.com/p2Yxaex.jpg'" /></a>
<nav class="menu-side">
This is a side menu
</nav>
</header>

<br />


<center>Content here
</center>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script> 
(function() {
           var body = $('body');
           $('.menu-toggle').bind('click', function() {
                body.toggleClass('menu-open');
                return false;
                });
          })();
</script>
</body>
</html>

css:

.menu {
    overflow-x:hidden;
    position: relative;
    left: 0px;
}

.menu-open {
    left: 231px;

}

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

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

}

.menu-side {
    background-color:#333;
    border-right:1px solid #000;
    color:#fff;
    position:fixed;
    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!

pppp
  • 231
  • 1
  • 11
mutfak
  • 21
  • 1
  • Are you looking for something like this [Detect Outside Click](http://stackoverflow.com/questions/152975/how-to-detect-a-click-outside-an-element) – natejd04 May 15 '16 at 06:18
  • None of those seem to work. If you think they should, which one would I put where and how would I edit it? – mutfak May 15 '16 at 10:26

1 Answers1

1

Did you mean clicking outside the navbar closes it?

This code works for me,

<a href="#" class="menu-toggle">Toggle menu</a>
<div id="example_menu" style="display:none">
    <a href="#">Test</a>
    <a href="#">Test</a>
    <a href="#">Test</a>
</div>

<script>
    $(document).ready(function () {
        $('.menu-toggle').hover(function () {
            $('#example_menu').show();
        });

        // when clicked outside
        $(this).click(function (e) {
            var el = $('#example_menu');

            if (!el.is(e.target) && el.has(e.target).length === 0) {
                el.hide();
            }
        });
    });
</script>
keziah
  • 564
  • 1
  • 6
  • 24
  • When I click off the nav bar it fades out the 'Test' links, however it doesn't make the nav bar close. – mutfak May 15 '16 at 08:50