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.

Ivar
  • 6,138
  • 12
  • 49
  • 61
  • 2
    When you say "reloading forever", do you mean it gets keeps reloading over and over again? or that the new page never loads? – DBS Aug 16 '21 at 09:51
  • Are you aware that this code will replace the last URL segment by `students`? Is that what you need to do? – Guerric P Aug 16 '21 at 09:57
  • Nothing in this code should cause infinite/repeated reloading. We can't help without a [mcve]. – Ivar Aug 16 '21 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. – Delmontee Aug 16 '21 at 10:56
  • actually the reload happened becayse of something else, i fixed that... still thanks a lot guys – Aazim Khaki Aug 16 '21 at 11:02
  • 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. – Ivar Aug 16 '21 at 11:29

1 Answers1

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 …)

TheEagle
  • 5,808
  • 3
  • 11
  • 39