steamfunk steamfunk - 2 months ago 14
jQuery Question

better implementation of on click toggle class jquery

Hello I was wondering if someone could help me out. I have some jquery code which adds a class to specific Divs in my page. I was wondering if there was a better way to implement the code, because it is glitchy. I have 5 Div IDs which i would like to add a visible class to. I also have one class which applies to all the div elements which should toggle an active class. I am fairly new to jquery and not sure if this is the proper way to implement it, please see my code below:

$('.graph-button').click(function() {
$(this).toggleClass("active");
});

//Get the Circles to Show text boxes by adding class
$('#value_button').click(function(){
$('#value_text').toggleClass("visible");
});
$('#history_button').click(function(){
$('#history_text').toggleClass("visible");
});
$('#vision_button').click(function(){
$('#vision_text').toggleClass("visible");
});
$('#offering_button').click(function(){
$('#offering_text').toggleClass("visible");
});
$('#future_button').click(function(){
$('#future_text').toggleClass("visible");
});


I would really appreciate the help. CHEERS!

Answer

Just toggle the class of the next element anytime a button is pressed

$('.graph-button').click(function() {
    $(this).toggleClass("active");
    $(this).next().toggleClass("visible");
});