Search code examples
javascriptevent-delegation

Event Delegation - event trigger with wrong class


I'm trying to create a slider with html- vanilla javascript. I'm able to open a modal, show a wide slider image and small images (thumbnails). Everything looks fine but when I click the thumbnails (which have "small_image" class) they trigger events, change image and add the same images to the thumbnails section again.

I checked the console with console.log(e.target.className) when I clicked any of the thumbnails and it shows "slider" class not "small_image" class.. Why is this happening and how can I fix this ?

Html section

<div id="photos" class="tabcontent">
    <div class="tabslider">
        <div>
            <img src="{{image_path("posts/5-1537128615.jpg")}}" class="slider">
        </div>
        <div>
            <img src="{{image_path("posts/6-1537128615.jpg")}}" class="slider">
        </div>
        <div>
            <img src="{{image_path("posts/7-1537128615.jpg")}}" class="slider">
        </div>
        <div>
            <img src="{{image_path("posts/8-1537128615.jpg")}}" class="slider">
        </div>
        <div id="myModal" class="modal">
            <span class="close cursor">&times;</span>
            <div class="modal-content">
              <!-- wide image -->
                <div class="mySlides">
                    <img class="show_slider" src="">
                </div>
              <!-- small images -->
                <div class="small_images"></div>

            </div>
        </div>
    </div>

</div>

Javascript section

document.querySelector(".tabslider").addEventListener("click", function (e) {
    if (e.target.className = "slider") {
        let smallImages = document.querySelector(".small_images"),
            images = document.querySelectorAll(".slider"),
            slider = document.querySelector(".show_slider"),
            sliderDiv = document.querySelector(".mySlides"),
            model = document.querySelector("#myModal");

        model.style.display = "block";

        images.forEach(function (image) {
            let img = Elementor.create("img", {"src": image.src, "class": "small_image"}),
                div = Elementor.create("div", {"class": "columnlightbox"},);
            div.appendChild(img);
            smallImages.appendChild(div);
        });

        slider.setAttribute("src", e.target.src);
        sliderDiv.style.display = "block";
    }
})

Solution

  • e.target.className = "slider"
    

    You are setting the value here, not comparing :D