0

As I was making a gallery for a webpage I ran into a problem with js automatically running the (next_image) function, after some searching around I found out it was due to the () after the statement. however, I can not for the life of me figure out how else to get the clicked_id to the next_image function.

So my question is: how can I make it so that the function runs only after clicking the button while still sending the clicked_id?

function opencase(clicked_id) {
                document.getElementById("right_arrow").addEventListener("click", next_image(clicked_id));
            }
            function next_image(photoid){
                console.log(photoid);
                photoid++;
                document.getElementById("disp").setAttribute("src", "images/image"+photoid+".jpg");
                console.log(photoid);
            }

Any help will be greatly appreciated :D

1
  • 1
    another alternative to brk's answer is to have next_image return a function. function next_image(id) { return function() { /* use id here */ } } Commented Aug 2, 2019 at 15:06

1 Answer 1

2

Instead of directly calling the function , call it from the addEventListener callback function

function opencase(clicked_id) {
  document.getElementById("right_arrow").addEventListener("click", function() {
    next_image(clicked_id)
  });
}

function next_image(photoid) {
  console.log(photoid);
  photoid++;
  document.getElementById("disp").setAttribute("src", "images/image" + photoid + ".jpg");
  console.log(photoid);
}

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.