0

So, I'm trying to run this code

document.location = "https://stackoverflow.com/questions/ask";
document.onload = function(){document.getElementById("title").value="My question";};

but it turns out that my function doesn't run the function. You can observe this by doing

document.location = "https://stackoverflow.com/questions/ask";
document.onload = function(){document.getElementById("title").value="My question";alert('Hi');};

My question is, what am I doing wrong? Why doesn't the function run?

PyRulez
  • 10,513
  • 10
  • 42
  • 87

1 Answers1

2

Something similar was asked here!

Here is a quote of the most important part of the accepted and most upvoted answer:

No, you cannot do it the way you want. Loading a new page closes the current document and starts loading a new document. Any code in your current document will no longer be active when the new page starts to load. - Source: Answer by jfriend00

Bee
  • 1,306
  • 2
  • 10
  • 24
  • Actually my question is probably a duplicate of that one. – PyRulez Mar 02 '18 at 01:10
  • Yeah, don't worry. I just like to quote the most important part of the answer of the original question just in case it gets deleted sometimes. – Bee Mar 02 '18 at 01:13
  • @DavidMichaelHuber That's really a non-argument. Why would a question with 16 upvotes and an accepted answer with 15 upvotes ever get deleted? – Robby Cornelissen Mar 02 '18 at 01:35
  • @RobbyCornelissen There is [this](https://meta.stackoverflow.com/questions/363892/what-should-be-done-if-a-question-has-its-duplicate-deleted?cb=1) question that made me think it is a good idea to do like I did. Do you think it is bad to give a quote that leads into the right direction? – Bee Mar 02 '18 at 01:37
  • 1
    I think the general consensus is that clear duplicates should be closed as such, and that replicating the answer just adds clutter to the site. The meta question that you're referring to, describes scenarios that are clearly not applicable here. The general guidelines are here: https://meta.stackexchange.com/questions/10841/how-should-duplicate-questions-be-handled – Robby Cornelissen Mar 02 '18 at 01:55
  • "*[...] and that replicating the answer just adds clutter to the site."* That's true I have to admit. I actually thought about users finding this (duplicate) question wanting an answer without going through another question. Anyway guidelines are guidelines! So I am going to go with them. Thanks for informing me! – Bee Mar 02 '18 at 02:04