0

I'd like to use a button on a homepage that when it links to the new page, changes the background color of the new page. In the code, I have two buttons. One is the boring button. It links to the page and does nothing else. The other is the purple button, which is supposed to link to the same page, and change the background color.

I've already tried linking both of the pages to the same script document. I've also tried using the 'DOMContentLoaded' event listener, which didn't work either.

Home page code:

  <button id="boringBtn">Press this button to go to a new page and do nothing</button>

  <button id="purpleBtn">Press this button to go to a new page and change the color</button>

  <script src="link-script.js">&lt;/script>

link-script code:

function newPage() {    
  window.location = "linked-page.html";    
}

function newPageWithColor() {    
  window.location = "linked-page.html";    
  document.body.style.background = "purple";    
}

document.getElementById("boringBtn").onclick = newPage;
document.getElementById("purpleBtn").onclick = newPageWithColor;
wazz
  • 4,953
  • 5
  • 20
  • 34
  • 1
    One option is to add parameters to your url, eg "linked-page?background=purple" (or "encode" this, eg `c=1` then your page checks if c==1 and sets background to purple). Or you could use localStorage. – freedomn-m Nov 01 '19 at 17:57
  • The page is refreshed when you navigate so the change in background will be reset. What you can do is link to 'linked-page.html?background=purple' and then in your script om that page have background set based on that https://stackoverflow.com/q/901115/1501613 – cYrixmorten Nov 01 '19 at 17:58

0 Answers0