简体   繁体   中英

jQuery onclick addclass/removeclass and add fade

The past three day I have been searching for a solution to my problem. I have seen a lot of people with the same question as I have, but not one solution fixes my problem. So I am again where I started and I am asking for the help of you friendly people!

I now have the following script running that works perfect for me:

$(".show_commentsandnotes_container").click(function () {
    $('.commentsandnotes_bg').addClass('show');
    $('.commentsandnotes_container').addClass('show');
});
$(".commentsandnotes_bg").click(function () {
    $('.commentsandnotes_bg').removeClass('show');
    $('.commentsandnotes_container').removeClass('show');
});

The only thing I can't get to work, is the fading in and out of elements. I have tried a lot of solution like toggle and show/hide, but this works the best for me. The only simple thing that I need is that fading is added to the script (1000 ms), I just can't work that out.

Can someone help me? Thanks in advance.

$(".show_commentsandnotes_container").click(function () {
    $('.commentsandnotes_bg').fadeIn(1000, function() {
       $('.commentsandnotes_bg').addClass('show');
    });
    $('.commentsandnotes_container').fadeIn(1000, function() {
       $('.commentsandnotes_container').addClass('show');
    });
});
$(".commentsandnotes_bg").click(function () {
    $('.commentsandnotes_bg').fadeOut(1000, function() { 
       $('.commentsandnotes_bg').removeClass('show');
    });
    $('.commentsandnotes_container').fadeOut(1000, function() { 
       $('.commentsandnotes_container').removeClass('show'); 
    });
});

As a side note, for more complex scenarios, a more controllable alternative is to use jQuery.animate() . Just be sure to really look into the documentation and know exactly what you want before diving into this. It is much more flexible, but not nearly as straightforward.

For example, an untested version of part of the code provided in the question :

$( "#show_commentsandnotes_container" ).click(function() {
  $("#commentsandnotes_bg" ).animate({
    opacity: 0.25,
    height: "toggle"
  }, 1000, function() {
     $("#commentsandnotes_bg").addClass("show");
  });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM