I'm relatively new to JavaScript and I've been struggling with using multiple onClick attributes. While I have some code that works, I feel like there might be a simpler and cleaner solution to my problem.
What I'm trying to achieve is a navigation menu where clicking on a hyperlink changes its background color and updates the content of a blog div. Additionally, when clicking on another hyperlink, it should change the background color and reset the previous one to its original state.
Here's what I have so far. It seems to work, but I'm not sure if this is the most efficient approach:
-- HTML
<div id="container">
<div id="navigation_bar">
<nav>
<ul>
<li class="red" id="1"><a href="#" onclick="showDiv1(this)">NavMenu1</a></li>
<li class="red" id="2"><a href="#" onclick="showDiv2(this)">NavMenu2</a></li>
<li class="red" id="3"><a href="#" onclick="showDiv3(this)">NavMenu3</a></li>
<li class="red" id="4"><a href="#" onclick="showDiv4(this)">NavMenu4</a></li>
</ul>
</nav>
</div>
<div id="blog">
<div id="category_1" style="display: none">
<img src="#" alt="xx" />
<article>
<p>Content of first navigation bar</p>
</article>
</div>
<div id="category_2" style="display: none;">
<article>
<p>Content of second navigation button</p>
</article>
</div>
</div>
</div>
JavaScript
function showDiv1(obj) {
var elchosen = document.getElementById('category_1');
elchosen.setAttribute('style', 'display:block;');
var spanID = obj.parentNode.id;
var newNode = document.getElementById(spanID);
var menus = document.getElementsByClassName("rood");
for (var i = menus.length - 1; i >= 0; i--) {
var elem = document.getElementById(menus[i].id);
elem.style.backgroundColor = "transparent";
}
newNode.style.backgroundColor = "red";
}
function showDiv2(obj) {
var elchosen = document.getElementById('category_1');
elchosen.setAttribute('style', 'display:none;');
var elchosen = document.getElementById('category_2');
elchosen.setAttribute('style', 'display:block;');
var spanID = obj.parentNode.id;
var newNode = document.getElementById(spanID);
var menus = document.getElementsByClassName("red");
for (var i = menus.length - 1; i >= 0; i--) {
var elem = document.getElementById(menus[i].id);
elem.style.backgroundColor = "transparent";
}
newNode.style.backgroundColor = "red";
}
It would be great if there's a more concise way to achieve this, perhaps using categories and functions like showDiv(n), to avoid repeating similar code for different operations as shown above.
Any advice or tips would be greatly appreciated, as I'm still learning and exploring JavaScript. Thank you!