Reputation: 3469
I have a button which I want to toggle between two 'functionalities.' I want it to toggle my menu open and close
I want to add onclick="openNav()"
on first click and then onclick="closeNav()"
on the second
html
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button" onclick="openNav()"></button>
I'm not sure the best way to do this, the code works if they are on two separate buttons.
EDIT: I am using Wordpress so all the javascript is in a separate .js
file brought in
Upvotes: 3
Views: 579
Reputation: 68933
Maybe you can call the functions based on some flag value:
var flag = true;
var navBtn = document.querySelector('#nav-icon');
navBtn.addEventListener('click', function(btn){
if(flag) openNav();
else closeNav();
flag = !flag;
});
function openNav(){
console.log('Open');
}
function closeNav(){
console.log('Close');
}
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button">Click</button>
Upvotes: 1
Reputation: 36564
You can change onclick
of the element at end of both functions.
let btn = document.getElementById('nav-icon');
function openNav(){
console.log('openNav called');
btn.onclick = closeNav
}
function closeNav(){
console.log('closeNav called');
btn.onclick = openNav
}
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button" onclick="openNav()"></button>
Upvotes: 2
Reputation: 44087
Just add a line to each of your functions:
In openNav()
:
document.getElementById("nav-icon").setAttribute("onclick", "closeNav()");
In closeNav()
:
document.getElementById("nav-icon").setAttribute("onclick", "openNav()");
Upvotes: 1
Reputation: 14413
You would typically have something like:
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button" onclick="toggleNav()"></button>
And the JS:
var navOpen = false;
function toggleNav(){
navOpen = !navOpen
// Do conditional show hide here based on navOpen
}
Upvotes: 1
Reputation: 50684
You could create a toggleNav
function which will alternative between executing both your openNav
and closeNav
functions by using a boolean like so:
let opened = false; // set the nav as closed by default
function toggleNav() {
if(!opened) { // if opened is false (ie nav is closed), open the nav
openNav()
} else { // else, if opened is ture (ie nav is open), close the nav
closeNav();
}
opened = !opened; // negate boolean to get opposite (t to f, and f to t)
}
function openNav() {
console.log("Opened Nav");
}
function closeNav() {
console.log("Closed Nav");
}
<button id="nav-icon" class="navbar-toggler hidden-sm-up" type="button" onclick="toggleNav()">Toggle Nav</button>
Upvotes: 1