0

What I am trying to do is dynamically add the URL of each image to an array whenever the user clicks a picture. I tried using the array method push() to add an image URL to an empty array but all it does is replace whatever image URL is already there with the new one you click.

$("img").on("click", function () {
      event.preventDefault()
      console.log(this);
      const gif = $(this).attr("src");
      let savedGif = []
      savedGif.push(gif)
      console.log(savedGif)
    })
1
  • How do you want to handle duplicate URLs? Commented Jan 13, 2020 at 16:51

1 Answer 1

3

You're emptying savedGif every time you click. Initialize it outside the onclick event:

let savedGif = []

$("img").on("click", function() {
    event.preventDefault()
    const gif = $(this).attr("src");
    if(!savedGif.includes(gif)){
        savedGif.push(gif)
    }
    console.clear()
    console.log(savedGif)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://placekitten.com/200/100" />
<img src="https://placekitten.com/200/120" />
<img src="https://placekitten.com/200/140" />
<img src="https://placekitten.com/200/160" />

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.