Using jQuery, I am trying to create a dynamic menu bar whose selections change as I click on different items.
Here is the simple HTML
<div >
<nav class='menubar'>
<button class='btn websites'>Websites</button>
<button class='btn contacts'>Contacts</button>
<button class='btn finance'>Finance</button>
</nav>
<div >
</div>
</div>
And the javascript
// click on navbar only
$($nav_menu).on('click', (e)=> {
console.log("Menu Bar")
$nav_menu.load('/main_menu.html');
})
// click on any button
$($nav_menu).on('click', $btn_websites, ()=> {
//$nav_menu.html("");
console.log("Websites")
//$nav_menu.load('/website_menu.html');
})
// click on any button
$($nav_menu).on('click', $btn_contacts, ()=> {
//$nav_menu.html("");
console.log("Contacts")
//$nav_menu.load('/contact_menu.html');
})
// click on any button
$($nav_menu).on('click', $btn_finance, ()=>{
//$nav_menu.html("");
console.log("Finance")
// $nav_menu.load('/finance_menu.html');
})
The problem is that regardless of which item I click on, or if I click only on the menu bar itself, all of the functions are executed. Console log shows that each function has fired.
Thank you
CodePudding user response:
The best you can do apart from what you are going is as below
$(".menubar .websites").on('click',(e)=>{
e.preventDefault();
load('/website_menu.html');
});
$(".menubar .finance").on('click',(e)=>{
e.preventDefault();
load('/finance_menu.html');
});
$(".menubar .contacts").on('click',(e)=>{
e.preventDefault();
load('/contacts_menu.html');
});
You will have to add another link to open the main menu. Make sure you have the load function to open the requested page ie
function load(page_path){
$.get(page_path, function(data) {
$(".workspace").html(data);
alert("Page hasloaded.");
});
}
CodePudding user response:
// assuming the following...
const $nav_menu = $("nav.menubar");
const $btn_websites = ".btn.websites";
const $btn_contacts = ".btn.contacts";
const $btn_finance = ".btn.finance";
const $workspace = $("div.workspace");
$($nav_menu).on('click', $btn_websites, (event) => {
console.log("Load Websites");
$workspace.html(event.target.textContent);
})
$($nav_menu).on('click', $btn_contacts, (event) => {
console.log("Load Contacts");
$workspace.html(event.target.textContent);
})
$($nav_menu).on('click', $btn_finance, (event) => {
console.log("Load Finance");
$workspace.html(event.target.textContent);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div >
<nav class='menubar'>
<button class='btn websites'>Websites</button>
<button class='btn contacts'>Contacts</button>
<button class='btn finance'>Finance</button>
</nav>
<div >
</div>
</div>