Everything works fine except one thing, I'd like it so when you have the .show
class already visible, it will fade again when you click on another of the #c-
divs.
$('[id^="c-"]').each(function(i){
$this = $(this);
$(this).text(i);
$(this).on('click',function(){
$('.show').fadeIn().text(i);
event.stopPropagation();
});
})
$(document).on('click', function(){
$('.show').fadeOut();
});
One of your problems is that you are not stopping the propagation because event
is not being defined. You'll have to use the parameter for the click
handler. Edit: Actually, it looks like event
is automatically passed - I did not realize this before now. However, I still think it best to put the event object as the parameter if you are going to use it - jQuery does this in their examples and it makes it more obvious.
I also notice you are caching this
but then not using that cached var. This means that every time you write $(this)
, it will have to rewrap that jquery object.
Then you can have a fadeOut and use the fadeIn as a callback for the fadeOut. This way if the .show
element is already shown, it will fadeOut first. I'd write it like this:
$('[id^="c-"]').each(function (i) {
$this = $(this);
$this.text(i);
$this.on('click', function (event) {
event.stopPropagation();
$show = $(".show");
$show.fadeOut(function () {
$show.fadeIn().text(i);
});
});
})