سؤال

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.

http://jsfiddle.net/7KdR6/1/

$('[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);
        });
    });
})

Fiddle

نصائح أخرى

You need to hide the element before using fadeIn on a visible element

$('[id^="c-"]').each(function (i) {
    var $this = $(this);
    $this.text(i);
    $this.on('click', function () {
        $('.show').hide().fadeIn().text(i);
        event.stopPropagation();
    });
})

Demo: Fiddle

Try calling .hide() before calling .fadeIn().

DEMO FIDDLE

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top