How would I be able to click a button on one page, that will enable another button on another page?
my javascript
function enableButton2() {
document.getElementById("button2").disabled = false;
document.getElementById("divbutton").hidden = false;
}
HTML
<input type="button" id="button1" value="button 1" onclick="enableButton2()"/>
<div id="divbutton" hidden>
<input onclick="window.location.href='menu.html'" type="button" id="button2" value="button 2" disabled />
</div>
this code works but will only work if both these buttons are on the same page, what I'm trying to do is separate them into their own pages but still work as intended, that is clicking the first button will make the second button appear.
Thanks in advance!
CodePudding user response:
You can use Broadcast Channel API to communicate between different tabs.
For example, declare the following on both pages:
const bc = new BroadcastChannel('button_disable');
bc.onmessage = function(event){
if(event.data == "hide"){
//hide the buttons
}else if(event.data == "show){
//show the buttons
}
}
Then, if you want to hide/show the button, simply dispatch a message:
bc.postMessage('hide');
CodePudding user response:
localStorage
would be an efficient approach if you also want to save the user's button choice. localStorage
allows you to store a value in the same origin, which means you just have to check whether the value was changed and differentiate which button should be enabled.
For example,
function enableButton2() {
localStorage.enabledButton = '2'
}
Then to check which button to enable, which would be used in the second page
setInterval(() => {
if (localStorage.enabledButton == "1") {
//Enable button 1
}
if (localStorage.enabledButton == "2") {
//Enable button 2
}
})