My knowledge of front-end web development is strongest in HTML and CSS, but when it comes to JavaScript, I feel like there must be a more efficient way to achieve the functionality I want.
On my website, I have a set of <li>
items that, when clicked, display a specific div. If another div is already visible (linked to a different <li>
item), it hides the previous one and shows the new one. Additionally, an active
class is assigned to the selected <li>
item for better user experience.
Below is the HTML and JavaScript code I'm currently using:
<li id="general">General</li>
<li id="blog">Blog</li>
<li id="twitter">Twitter</li>
And here's the JavaScript function (which I admit is not the most elegant solution):
$(document).ready(function() {
$("#general").addClass("active");
$("#general").click(function() {
$(".data-tab").hide();
$(".settings-general").toggle();
$("li").removeClass("active");
$("#general").addClass("active");
});
$(".settings-twitter").hide();
$("#twitter").click(function() {
$(".data-tab").hide();
$(".settings-twitter").toggle();
$("li").removeClass("active");
$("#twitter").addClass("active");
});
$(".settings-blog").hide();
$("#blog").click(function() {
$(".data-tab").hide();
$(".settings-blog").toggle();
$("li").removeClass("active");
$("#blog").addClass("active");
})
});
The current setup works fine, but I can't help but think there's a cleaner jQuery method to achieve the same result. Any suggestions for a JavaScript beginner like me?