I'd like to create a navbar that will collapse when the screen is below a certain size, using jQuery, HTML and CSS, the website uses Wordpress, hence the
jQuery(function($) {...
Here's my code :
<div class="navbar-nav" id="nav-responsive">
<a class="nav-item nav-link" href="#">Créer mon plateau de fromages |</a>
<a class="nav-item nav-link" href="<?php echo get_site_url(); ?>/l-histoire-lepetit">L'histoire Lepetit |</a>
<a class="nav-item nav-link" href="<?php echo get_site_url(); ?>/le-camembert-lepetit">Le camembert Lepetit |</a>
<a class="nav-item nav-link" href="<?php echo get_site_url(); ?>/univers">L'univers Lepetit |</a>
<a class="nav-item nav-link" href="<?php echo get_site_url(); ?>/conseil">Les conseils Lepetit</a>
</div>
<a href="javascript:void(0)" class="bar-nav-container" onclick="showNav()">
<img src="<?php echo get_stylesheet_directory_uri(); ?>/img/menu-bar.png" id="bar-nav">
</a>
<script>
jQuery(function ($) {
function showNav() {
// var navBlock = $('nav-responsive')
$('#bar-nav-container').click(function () {
alert("click");
});
}
showNav();
});
</script>
I want the bar-nav-container to execute showNav when it is clicked on. The alert("click") is just a way to make sure my function is really called. What's wrong with my code ? When I click it says showNav is not defined.. I tried to call the function with :
onclick="$(showNav())"
And it still doesn't work. Any help please ? Thanks !
1 Answer 1
"bar-nav-container" is your class and function should be outside. your script should be something like this.
function showNav(){
//do whatever you want
}
$(document).ready(function(){
$('.bar-nav-container').click(function () {
alert("click"); showNav();
});
});
showNav()is not available in the "global namespace" (in JS parlance, you say "on the window object"). It is defined in a closure and only available there, not outside! This is, in fact, desired bahaviour if used correctly and can prevent you from doing Bad Things ;-)