Reputation: 287
I need some help creating some jQuery for my site beemo-demo.squarespace.com. I am building Beemo from Adventure Time for practice. I am trying to make him have multiple faces, and when you click on a button (like the Red Button) it hides the current face and displays the face attached to that button.
I currently have the following jQuery which works to display the id="face-not-amused" when the red button is clicked, however the current face id="face-normal" does not hide.
$(document).ready(function() {
$("#circle-red").on('click', function(e){
$("#face-not-amused").toggle();
});
});
I am thinking I need to use .find() 'visible' for the id="face-wrapper" to find the current active div, then use .hide() to hide that div when a button is clicked. I am not sure how to go about this and am looking for help. I will eventually have multiple faces for him, as right now I only have two faces.
Upvotes: 0
Views: 1592
Reputation: 1126
You can keep a relation between the associated face and button, e.g. same class or similar id. Then handle the click event. If new buttons will be added in future then only this relation need to be added but the click function can remain the same.
So if you have divs like
<div class='face one'>face one</div>
And buttons like
<button id='one' class='btnFace one'>One</button>
You can write click event as
$('button').click(function(){
var clickedId = $(this).attr('id');
$('.face').hide();
$('div.'+clickedId).show();
});
See this example fiddle.
Upvotes: 1
Reputation: 425
CSS
#face-normal { display: block; }
#face-not-amused { display: none; }
.amused #face-normal { display: none; }
.amused #face-not-amused { display: block; }
JS
$(document).ready(function() {
$("#circle-red").on('click', function(e){
$("#face-not-amused").parent().toggleClass('amused');
});
});
Upvotes: 0
Reputation: 325
Your thinking is correct.
Use
$("#face-wrapper").find("div:visible").hide();
Be sure to place it before toggling $("#face-not-amused");
Upvotes: 1