Reputation: 153
Say i have this html file with several divs and several buttons(or links).
i don't want to more than one div to ever appear simultaneously. I want to, once you click a button/link, any div displayed disappears and its corresponding div replaces it on screen.
<button onclick="toggleByClass('1');">Toggle 1</button>
<button onclick="toggleByClass('2');">Toggle 2</button>
<button onclick="toggleByClass('3');">Toggle 3</button>
<div class="1">content1</div>
<div class="2">content2</div>
<div class="3">content3</div>
Up to now i only managed to toggle the divs, but that allows more than one to appear simultaneously.
Upvotes: 1
Views: 44
Reputation: 11328
You could clean it up a little, starting from HTML:
<button >Toggle 1</button>
<button >Toggle 2</button>
<button >Toggle 3</button>
<div class="div">content1</div>
<div class="div">content2</div>
<div class="div">content3</div>
Point of the class is to be reusable, so, give all elements same class...
To hide all divs at the start, if you want, do it by CSS:
.div {
display:none;
}
And jQuery:
$( "button" ).click(function() {
$('.div').hide();
$('.div').eq($(this).index()).show();
});
I've used these fine built-in jQuery functions:
There are more ways, of course (by using data attributes, etc, etc...)
Demo: https://jsfiddle.net/zL24hkur/
Upvotes: 0
Reputation: 516
I have tried in Jquery. It might help you
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$('.content_div').hide();
$(document).on('click','.toggle_btn',function()
{
$('.content_div').hide();
var div_to_show = $(this).attr('id');
$('.'+div_to_show ).slideToggle();
});
});
</script>
</head>
<body>
<button class="toggle_btn" id="1">Toggle 1</button>
<button class="toggle_btn" id="2">Toggle 2</button>
<button class="toggle_btn" id="3">Toggle 3</button>
<div class="1 content_div">content1</div>
<div class="2 content_div">content2</div>
<div class="3 content_div">content3</div>
</body>
Upvotes: 1
Reputation: 379
U could use jQuery's toggle()
function, or just call the show() / hide()
functions if you just want to show/hide the divs, if they are already in your html, as in your example.
Just remember to hide()
all the divs before calling show()
on the new one, to make only one visible at a time.
Another approach you could use, is to define a .hidden
class in your css, and append that to the classList whenever you want to hide that div.
.hidden { visible: none; }
But then you might need to query for the div's using ID instead of by class, as that might cause a problem when changing the class-attribute dynamically. :)
Upvotes: 1