0
window.onload = prepareButton;

function prepareButton() {
  document.getElementById('slist').onclick = function() {
    window.location = "students";
  }
}

Once I click on a slist element which happens to be a <p> tag structured like this

<p type="button" id="slist" class="active">Student List</p>

It keeps the page reloading forever, I don't know why.

6
  • 2
    When you say "reloading forever", do you mean it gets keeps reloading over and over again? or that the new page never loads? Commented Aug 16, 2021 at 9:51
  • Are you aware that this code will replace the last URL segment by students? Is that what you need to do? Commented Aug 16, 2021 at 9:57
  • Nothing in this code should cause infinite/repeated reloading. We can't help without a minimal reproducible example. Commented Aug 16, 2021 at 10:06
  • I tried to help you but was downvoted, so I've removed it. I hope you find a solution. Because the one I gave worked for me. Commented Aug 16, 2021 at 10:56
  • 1
    @James The code in the question worked just as well. Your answer didn't explain why changing it would make any difference (and in fact, they didn't made a difference.) As expected (and confirmed by OP), the problem was elsewhere. Those downvotes seem more than justified. Commented Aug 16, 2021 at 11:29

1 Answer 1

0

You should assign a whole URL or path to window.location, not just a word:

window.onload = prepareButton;

function prepareButton() {
  document.getElementById('slist1').onclick = function() {
    window.location = "stackoverflow.com/questions";
  }
  document.getElementById('slist2').onclick = function() {
    window.location = "/questions";
  }
  document.getElementById('slist3').onclick = function() {
    window.location = "../..";
  }
}
All these buttons will take you to the StackOverflow questions overview.
<p type="button" id="slist1">Using the whole URL</p>
<p type="button" id="slist2">Using an absolute path</p>
<p type="button" id="slist3">Using a relative path</p>

(Sorry - for some reason it doesn't work inside a StackSnippet …)

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.