I’m pretty new to Jquery and Javascript and was am working on a project that I am sure has a much simpler way of coming to the same functionality. The following is a simplified version of what I am doing:
HTML
<a class="link1" href="#">Link 1</a>
<a class="link2" href="#">Link 2</a>
<a class="link3" href="#">Link 3</a>
<div id="div1" style="display: hidden;">Content</div>
<div id="div2" style="display: hidden;">Content</div>
<div id="div3" style="display: hidden;">Content</div>
Jquery
$(".link1").click(function(){
$("#div2, #div3").hide();
$("#div1").show();
$(".link2, .link3").removeClass("active");
$(".link1").addClass("active");
});
$(".link2").click(function(){
$("#div1, #div3").hide();
$("#div2").show();
$(".link1, .link3").removeClass("active");
$(".link2").addClass("active");
});
$(".link3").click(function(){
$("#div1, #div2").hide();
$("#div3").show();
$(".link1, .link2").removeClass("active");
$(".link3").addClass("active");
});
So basically each link is immediately hiding both non-corresponding divs, even if they are not necessarily visible and also removes the active class on the other links even if they are not applied (to ensure that they are removed) then shows the corresponding div and adds an active class to the link. I am wondering if there is an easier way to create this functionality without having to hide all other divs and remove all active classes to ensure that nothing but the one I want visible is showing.
Thanks so much for any help you can provide!!
You could change your HTML a little to make things easier, for example:
And then use a simple function to perform what I think you want:
See a demo here The code is also explained (commented) on the demo