0

JS fiddle: http://jsfiddle.net/d9nat0gk/20/

let album_images_slider = new Swiper("#album_images_slider", {
    direction: "horizontal",
    slidesPerView: 1,
    loop: true,
    allowTouchMove: false,
    speed: 600,
    autoplay: {
        delay: 3000
    },

    navigation: {
        nextEl: ".swiper-button-next",
        prevEl: ".swiper-button-prev"
    }
});

$(function() {
    console.log("hello");


    $("#album_images_slider").click(function(e) {
        console.log("hello, mate!");
        console.log(e.target.className);
        if (e.target.classList.contains("swiper-slide")) {
            console.log("hello!");
            $("body *").hide();
            $("body").before(`<div class="layer">Hey!</div>`);
        }
        
    });
    
    $(".layer").on("click", function() {
        console.log("Hi");
        $(".layer").remove();
    });
});

Block .layer is succesfully displayed on the screen, but for some reason when I click on .layer, .layer click handling isn't invoked.

What is the problem? And how can I solve that?

Any help would be highly appreciated!

terrymorse
  • 6,771
  • 1
  • 21
  • 27
Coder4Fun
  • 135
  • 1
  • 14

1 Answers1

-1

The evaluation of the method $(".layer").on is performed on the elements when you call it, so if you try to console.log($(".layer")) just before that line, you will see that there are no elements with .layer at that point.

You should create and hide the <div.layer> at the start of your script or in the HTML, otherwise you can move the $(".layer").on(...) piece of code after you create the element (after $("body").before("<div class="layer">Hey!</div>");)

DDomen
  • 1,808
  • 1
  • 7
  • 17