Im attempting to build a website where there is an absolute centered Div with content in it. I want the content to change based on the several clickable buttons on the side. In order to do so I thought the best case might be to create several child divs of the same class and parent and hide the non relevant content and only show the content associated with the clicked link. I can write out 1 million
document.getElementById("ImAnId").onclick = function helpMePlease( {
document.getElementById("ImAlsoAnId").style.display="none";
}
lines of code. but is there a faster more simpler way to do this?
Give the buttons an id
and the corresponding container a similar id
(make it different from button's by concatinating some string). for example, I am giving the button id="red"
and to the corresponding div id="redD"
. Then it would make your javascript a whole lot shorter.
Instead of id
, you can also work with any custom attribute.
Here's a working snippet.
$(".links").click(function(){
var divId = "#"+ $(this).attr("id") + "D";
$(".divs").removeClass("active");
$(divId).addClass("active");
});
.con{
position:relative;
width:100%;
margin:0;
height:150px;
}
.divs{
position:absolute;
width:100px;
margin:0;
bottom:0;
left:0;
border:1px solid black;
height:100px;
display:none;
}
.divs.active{
display:block;
}
#redD{
background-color:red;
}
#greenD{
background-color:green;
}
#blueD{
background-color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="con">
<button class="links active" id="green">green</button>
<button class="links" id="blue">blue</button>
<button class="links" id="red">red</button>
<div class="divs active" id="greenD"></div>
<div class="divs" id="redD"></div>
<div class="divs" id="blueD"></div>
</div>
Give each button a data attribute that contains the ID of the related DIV, e.g.
<button class="link" data-div="ImAlsoAnId">Click me</button>
Then hide all the DIVs of the given class, and show the selected one.
$(".link").click(function() {
$(".divclass").hide();
$('#' + $(this).data("div")).show();
});
You could also use the jQuery UI Tabs plugin.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With