0

I'm building a list of images dynamically. What I want to happen is when a user clicks the close text (inside my DIV element) the code will delete that particular image (list element). The code below does that the FIRST time the DIV is selected. After that it seems to ignore my div event listener and jump straight into the jquery on click function.

function removeItem(){

var test = document.querySelector('li > div').addEventListener('click', function(){
    $(document).on('click', 'li', function () {
        var photoId = (this.id);
        $("#"+photoId).remove();
    });
});

How can I make it so it will ALWAYS run when the DIV is selected instead of just the first time?

I'm new to learning about JavaScript so any help is appreciated!

0

1 Answer 1

1

When the user clicks on the DIV, you're not removing anything, you're just adding a new click listener on all LIs that removes that LI. Then the user needs to click again to trigger the second handler. It should simply be:

$(document).on('click', 'li > div', function() {
    $(this).parent().remove();
});

BTW, there's no point in writing

    var photoId = (this.id);
    $("#"+photoId).remove();

It's simply $(this).remove(). Why go searching for an ID when you already have a reference to the element itself?

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.