Reputation: 6555
I'm new to jQuery and trying to work out how to achieve the following...
I have two div shown below, I want group
div to show on load but not single
div then onclick of group
or single
I need toggle between the two. How can this be done. This is what I have so far.
Send to: <a href="">Group</a> | <a href=""> Single<</a>
<div id="group">I'm a group</div>
<div id="single">I'm a single object</div>
UPDATE:
So something like this seems to work for me....
$("#link").click(function(e) {
e.preventDefault();
$("#divA, #divB").toggle();
$(this).text(function(i, text) { return (text == "Show viewA") ? "Show viewB" : "Show viewA" });
});
but divB does not show.
Upvotes: 1
Views: 9727
Reputation: 11
This is the best way to switch between two div
elements:
$("#show_Blue").click(function(){
$("#Blue").toggle();
$("#Red").hide();
});
$("#show_Red").click(function(){
$("#Red").toggle();
$("#Blue").hide();
});
There's a demo HERE
Upvotes: 1
Reputation: 8354
Looking at your example I have create a simple script that will work nice for your needs.
<script>
$(document).ready(function() {
var $divA = $('#a'),
$divB = $('#b'),
$link = $('#link');
$diplaytext = $('#display_text');
// Initialize everything
$link.text( 'Show Single' );
$diplaytext.text( 'Group' );
$divA.hide();
$link.click(function(){
// If A is visible when the link is clicked
// you need to hide A and show B
if( $divA.is( ':visible' ) ){
$link.text( 'Show Single' );
$diplaytext.text( 'Group' );
$divA.hide();
$divB.show();
} else {
$link.text( 'Show Group' );
$diplaytext.text( 'Single Here' );
$divA.show();
$divB.hide();
}
return false;
});
});
</script>
then...
display text: <span id="display_text"></span> | change: <a href="#" id="link" ></a>
<div id="a">a</div>
<div id="b">b</div>
Upvotes: 2
Reputation: 3299
Change your code to the following
Send to: <a data-div="group" href="#">Group</a> | <a data-div="single" href="#"> Single</a>
<div id="group">I'm a group</div>
<div id="single">I'm a single object</div>
<script>
$(document).ready(function(){
$("#single").css("display", "none");
$("a").click(function(e){
e.preventDefault(); // This prevents the link behaviour
$("div").css("display", "none");
$("#"+ $(this).attr("data-div")).css("display", "block");
});
});
</script>
Upvotes: 2
Reputation: 12172
Just hide them all, then unhide the one that was just clicked.
Send to: <a href="#" data-target="group" class="target">Group</a> | <a href="#" data-target="group" class="target">Single</a>
<div id="group" class="toggle">I'm a group</div>
<div id="single" class="toggle">I'm a single object</div>
Then use this jQuery:
$('.target').on('click', function(e) {
e.preventDefault();
$('.toggle').hide();
$( '#' + $(this).data('target') ).show();
});
Upvotes: 2