'Run location.replace when the “control” key is clicked
document.addEventListener('keydown', (event) => {
var name = event.key;
var code = event.code;
if (name === 'Control') {
location.replace(classroom.google.com)
}
if (event.ctrlKey) {
alert(`Combination of ctrlKey + ${name} \n Key code Value: ${code}`);
} else {
alert(`Key pressed ${name} \n Key code Value: ${code}`);
}
}, false);
// Add event listener on keyup
document.addEventListener('keyup', (event) => {
var name = event.key;
if (name === 'Control') {
location.replace(classroom.google.com)
}
}, false);
How currently when I press the control key, nothing happens. If I make it run an alert instead, then the alert will successfully run. Do I need to use the window.location function instead?
Solution 1:[1]
The issue with your code is that you aren't passing a string to location.replace().
Right now, your code looks like this.
location.replace(classroom.google.com);
The issue with this code is that you are not surrounding it with quotes to make it a string, so JavaScript thinks that you are referencing a property of an object, of an object.
Below is what JavaScript thinks is happening.
const classroom = {
google: {
com: undefined,
}
};
console.log(classroom.google.com); // undefined
To fix it, simply surround your parameter in quotes, as so.
location.replace("classroom.google.com");
This should successfully redirect you to classroom.google.com!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Arnav Thorat |
