Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trialSuzanne Cranen
7,497 PointsResponsive menu, click outside of nav
Hello,
I am making a website and of course I want to make it responsive, so I wanted to make a menu that looks different on a smaller screen than on a bigger screen. For the smaller screen I added an image and when you click on the image "menu" the nav toggles between hide and show. But I also want it to hide when I click outside of the navigation or the image. I have search a lot on the internet and I cannot find any solution which will work with my code, so is there anyone who can help me?
The website I am building is www.odinwesten.nl/test/ This is my code:
<script src="js/jquery-1.9.1.js"></script>
<script>
$(document).ready(function(){
$("#menu").bind("click", function(){
$("nav").toggle();
event.preventDefault();
});
});
</script>
</head>
<body>
<header>
<div id="afb">
<a><h1>Odin Westen</h1></a>
<img src="img/header.png" alt="Odin Westen" />
<a href="#" alt="menu" id="menu"><img src="img/Knopje.png" alt="menu" /></a>
</div>
<nav>
<ul>
<li class="home <?php if ($section == "home") { echo "on"; }; ?>"><a href="index.php">Home</a></li>
<li class="biografie <?php if ($section == "biografie") { echo "on"; }; ?>"><a href="biografie.php">Biografie</a></li>
<li class="foto <?php if ($section == "foto") { echo "on"; }; ?>"><a href="foto.php">Foto<span>'</span>s</a></li>
<li class="video <?php if ($section == "video") { echo "on"; }; ?>"><a href="video.php">Video<span>'</span>s</a></li>
<li class="contact <?php if ($section == "contact") { echo "on"; }; ?>"><a href="contact.php">Contact</a></li>
</ul>
</nav>
</header>
2 Answers
Daniel Quaidoo
23,937 Points$(document).click(function() {
$("nav").hide();
});
$("#menu").click(function(e) {
e.stopPropagation();
return false;
});
Try this
Daniel Quaidoo
23,937 PointsYour nav menu already hides when you click on the image. If you want it to hide when outside the nav is clicked, you could use javascript and on click event function if the nav link is not clicked (i.e. anywhere apart from the nav) hide the nav menu
Suzanne Cranen
7,497 PointsAnd how can I write that I have to click anywhere apart from the nav?
Suzanne Cranen
7,497 PointsSuzanne Cranen
7,497 PointsIt's working :D thank you very much!