JQuery $("body").append() not working on "first click"

Viewed 29

I was trying to create a lightbox that triggers on a button click. I already have a lightbox that triggers on click on a div in the same document.ready that works perfectly, BUT the one on the button doesn't work the first time I click it. Then, works perfectly. Well, I don't want to create a tooltip that says "please click it twice first time", so how can I fixed? (If anyone can also explain to me why this happens would be marvelous)

$(document).ready(function () {
    //BUTTON CLASS
    $(".focosBTN").click(function () {
        $("body").append("<div class='img-popup'></div>");
        $(".img-popup").click(function () {
            $(".img-popup").fadeOut(500, function () {
                $(this).remove();
            }).addClass("lightboxfadeout");
        });
        $(".focosBTN").click(function () {
            $(".img-popup").fadeIn(500);
        });
    });
    //DIV CLASS
    $(".lightbox").click(function () {
        let imgsrc = $(this).find('.lightboxImg').attr('src');
        $("body").append("<div class='img-popup'><img src='" + imgsrc + "'></div>");
        $(".img-popup").click(function () {
            $(".img-popup").fadeOut(500, function () {
                $(this).remove();
            }).addClass("lightboxfadeout");
        });
    });
    $(".lightbox").click(function () {
                $(".img-popup").fadeIn(500);
    });
});
0 Answers
Related