I have a navigation bar with links that lead to different parts to my Webpage, I want it so that in JavaScript I make a command and the link will be pressed and the webpage will be changed.
My Navigation Bar
// Current JavaScript Method (Not Working)
document.getElementById("section2Button").click();
<nav class="navbar navbar-expand-sm bg-primary navbar-dark justify-content-center fixed-top">
<ul class="navbar-nav">
<li id="section1Button" class="nav-item">
<a class="nav-link" href="#section1">Colleges</a>
</li>
<li id="section2Button" class="nav-item">
<a class="nav-link" href="#section2">College Selected</a>
</li>
<li id="section3Button" class="nav-item">
<a class="nav-link" href="#section3">About Me</a>
</li>
</ul>
</nav>
document.querySelector("#section2Button a").click();
You need to query to a tag. And you can put it into any function you want to execute. For example, I put this action into a button.
You can see full demo here.
function your_command() {
// Fixed query
document.querySelector("#section2Button a").click();
}
<button onclick="your_command()">Test command</button>
<nav class="navbar navbar-expand-sm bg-primary navbar-dark justify-content-center fixed-top">
<ul class="navbar-nav">
<li id="section1Button" class="nav-item">
<a class="nav-link" href="#section1">Colleges</a>
</li>
<li id="section2Button" class="nav-item">
<a class="nav-link" href="#section2">College Selected</a>
</li>
<li id="section3Button" class="nav-item">
<a class="nav-link" href="#section3">About Me</a>
</li>
</ul>
</nav>
<h2 id="section1">Section 1</h2>
<h2 id="section2" style="margin-top: 100px">Section 2</h2>
<h2 id="section3" style="margin-top: 100px">Section 3</h2>
You need to add an Event Listener.
var htmlElement = document.getElementById("section2Button");
htmlElement.addEventListener('click', function() {
console.log('clicked');
});
see demo
var htmlElement = document.getElementById("section2Button");
htmlElement.addEventListener('click', function() {
console.log('clicked');
});
<nav class="navbar navbar-expand-sm bg-primary navbar-dark justify-content-center fixed-top">
<ul class="navbar-nav">
<li id="section1Button" class="nav-item">
<a class="nav-link" href="#section1">Colleges</a>
</li>
<li id="section2Button" class="nav-item">
<a class="nav-link" href="#section2">College Selected</a>
</li>
<li id="section3Button" class="nav-item">
<a class="nav-link" href="#section3">About Me</a>
</li>
</ul>
</nav>