Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding second functionality to a single button

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

like image 570
user3550879 Avatar asked Jun 09 '26 13:06

user3550879


1 Answers

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>
like image 50
Maheer Ali Avatar answered Jun 12 '26 01:06

Maheer Ali



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!