Is there a way to use a specific keyboard input to alter the characteristics of shapes on my webpage?

Is there a way to change certain attributes of a shape onscreen when a specific key is pressed by the user? For example, can I make it so that pressing "a" changes the color of the shape?

I attempted to modify a mouse rollover event to work with the desired key press input.

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" href="css/screen.css">
<style>

.box1{
background:#1E90FF;
width: 1000px;
height:100px;
float:right;
margin: 0px 0px 0px 0px;

}
.circle {
height: 200px;
width: 200px;
background-color:  #1E90FF;
border-radius: 50%;
}
.toprectangle {
height: 80px;
width: 200px;
background-color: #1E90FF;
float:right;
margin: 0px 40px 20px 80px;
border: 1px solid #1E90FF;


}

.square {
height: 80px;
width: 200px;
background-color: #1E90FF;
float:right;
margin: 10px 40px 10px 1000px;
border: 1px solid #1E90FF;
<!--Third square down-->

}
.box2{
background:#1E90FF;
width: 1400px;
height:100px;
float:right;
margin: 60px 0px 0px 0px;
<!--rectangle at the bottom-->


}

.box3{
background:#1E90FF;
width: 200px;
height:600px;
margin: 0px 20px 130px 0px;
<!--rectangle going up the side-->
}
.circle1{
     height: 200px;
 width: 200px;
 background-color:  #1E90FF;
 border-radius: 50%;
 margin: 10px 500px 0px;

}

</style>
</head>



<body>


<script>
 function onkeypress(evt);
if(onkeypress == 49):
.toprectangle {
height: 80px;
width: 200px;
background-color: #ff78ff;
float:right;
margin: 0px 40px 20px 80px;
border: 1px solid #1E90FF;
}

</script>
<div class="box1"></div>
</div>
<div class="circle"></div>
<div class="circle1"></div>
<div class="toprectangle"></div>
<div class="square"></div>
<div class="square"></div>
<div class="box3"></div>
<div class="box2"></div>
<svg width="500" height="150">  
  

</body>
</html>

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Page Title</title>
<link rel="stylesheet" href="css/screen.css">
<style>
</style>
</head>
<body>

.toprectangle {
height: 80px;
width: 200px;
background-color: #1E90FF;
float:right;
margin: 0px 40px 20px 80px;
border: 1px solid #1E90FF;


}
<script>
 function onkeypress(evt);
if(onkeypress == 49):
.toprectangle {
height: 80px;
width: 200px;
background-color: #ff78ff;
float:right;
margin: 0px 40px 20px 80px;
border: 1px solid #1E90FF;
}
</script>
<div class="box1"></div>
</div>
<div class="circle"></div>
<div class="circle1"></div>
<div class="toprectangle"></div>
<div class="square"></div>
<div class="square"></div>
<div class="box3"></div>
<div class="box2"></div> 
  

</body>
</html>

The goal is to have different shapes change colors based on the user's key presses, but currently, the code does not respond to any inputs.

Answer №1

Alright, so there are a few issues in your code that need to be addressed. Firstly, your JavaScript syntax is incorrect.

Incorrect approach

function onkeypress(evt);
    if(onkeypress == 49)

Correct approach

function onkeypress(evt) {

    if ( /* add your condition here */ ) {
        /* add your code here */
    }
}

In addition, you need to add an event listener to your function. This listener will listen for specific events and call a function (your callback). You can find more information here. Here's how you can use it:

document.addEventListener("keypress", onkeypress); // Add the listener

function onkeypress(e) {
    /* Your callback function */
}

Alternatively

document.addEventListener("keypress", (e) => {
    /* Your callback function */
})

Furthermore, your CSS within the second snippet is not placed correctly. It should be enclosed within the <style></style> tag. Additionally, your <script></script> tags must be placed at the end of the body for proper functionality. Take a look at the corrected code below.

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Page Title</title>
    <link rel="stylesheet" href="css/screen.css">
  <style>
    .toprectangle {
        height: 80px;
        width: 200px;
        background-color: #1E90FF;
        float:right;
        margin: 0px 40px 20px 80px;
        border: 1px solid #1E90FF;
    }
  </style>
</head>
<body>

    <div class="box1"></div>
    <div class="circle"></div>
    <div class="circle1"></div>
    <div class="toprectangle"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="box3"></div>
    <div class="box2"></div>


  <script>
    document.addEventListener("keypress", onkeypress);
      function onkeypress(e) {
        console.log(`Letter: ${e.key} with code ${e.keyCode}`);
        if (e.keyCode == 97) {
          console.log('The letter `a` has been pressed!');
          let topRectangle = document.getElementsByClassName("toprectangle");
          console.log(topRectangle)
          topRectangle[0].style.backgroundColor = "#000"
        }
    }
</script>

</body>
</html>

Answer №2

It seems like there are some issues in your code that need to be addressed.

Firstly, it appears that you have CSS styling defined without enclosing it properly within your HTML structure.

Secondly, there are errors in your JavaScript function and its purpose is not clear. It's essential to identify the intended functionality of this function for successful implementation.

To address these issues, here is a suggestion to change the background-color on pressing Enter key using Vanilla JavaScript & jQuery:

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Page Title</title>
    <script src="https://code.jquery.com/jquery-1.12.4.js"></script>
    <style>
    </style>
</head>

<body>

    <style>
        .toprectangle {
            height: 80px;
            width: 200px;
            background-color: #1E90FF;
            float: right;
            margin: 0px 40px 20px 80px;
            border: 1px solid #1E90FF;


        }
    </style>

    <script>

        /* WITH VANILLA JAVASCRIPT */
        document.onkeydown = function (evt) {
            evt = evt || window.event;
            if (evt.keyCode == 13) {
                let elements = document.getElementsByClassName('toprectangle');
                let requiredElement = elements[0];
                requiredElement.style.background = "green";
            }
        };

        /* WITH JQUERY */
        $(document).on('keypress', function (e) {

            if (e.which == 13) { // If you press "Enter" key
                $(".toprectangle").css({
                    "background-color": "green"
                })
            }
        });
    </script>



    <div class="box1"></div>
    </div>
    <div class="circle"></div>
    <div class="circle1"></div>
    <div class="toprectangle"></div>
    <div class="square"></div>
    <div class="square"></div>
    <div class="box3"></div>
    <div class="box2"></div>


</body>

</html>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

index.html: using jquery for selecting colors

I attempted to integrate a jQuery plugin into my application, but it doesn't seem to be working. In the head section of my code, I have included: <link rel="stylesheet" media="screen" type="text/css" href="./style/colorpicker.css" /> <script ...

A ReferenceError was thrown because angular is not defined within the angular-moment.js script

After spending an hour trying to figure out what went wrong, I still can't solve this problem. I've searched on stackoverflow for answers, but nothing seems to be helpful. The issue arises when trying to integrate Moment js into my project. Che ...

Firefox is mistakenly interpreting a pasted image from the clipboard as a string instead of a file, causing

I am facing an issue where I am attempting to extract images from a contenteditable div using the paste event. The code works perfectly in Chrome but does not function as expected in Firefox. I have implemented the following code: $(window).on("paste& ...

The function type '(state: State, action: AuthActionsUnion) => State' cannot be assigned to the argument

I have encountered a persistent error in my main.module.ts. The code snippet triggering the error is as follows: @NgModule({ declarations: [ PressComponent, LegalComponent, InviteComponent ], providers: [ AuthService ], imports: ...

Adding flair to a fresh element and then removing it upon its inception

I'm working with a JavaScript code that creates a new element when a button is clicked. I have a question about it. Here's the JavaScript code snippet: var comment = document.querySelector("#AddComment"); var req = new XMLHttpRequest(); if(comm ...

What is the best way to incorporate a dynamic background in NextJS using Tailwind?

I have a poster image that I want to use as a background image, fetched from MovieDb. I tried putting it inside the className like this: className={bg-[url('${path}')] h-screen bg-cover bg-center text-white border-b-8 border-b-solid border-b-sla ...

Why isn't the Head component producing any visible results in the DOM when using Next.js?

Struggling to get the <Head> component working, but it's not reflecting any changes in the DOM. Take a look at my page.js: import Head from 'next/head' export default function Home() { return ( <> <Head> & ...

Utilizing ng-options within an ng-repeat to filter out previously chosen options

Facing a simple problem and seeking a solution. I am using ng-repeat to dynamically create select boxes with ng-options displaying the same values. The ng-repeat is used to iterate through model options. <div data-ng-repeat="condition in model.condit ...

Determine the height of an element within an ng-repeat directive once the data has been fetched from an

After sending an ajax request to fetch a list of products, I use angular's ng-repeat to render them. I am attempting to retrieve the height of a div element that contains one product in the list. However, the console always displays "0" as the result ...

Should I generate an array or pull data directly from the database?

Hey there, I've got this JavaScript app and could really use some input or tips. Here's the idea: Users log in to try and defeat a 'boss', with each player working together in the game. Let's say the 'boss' has 10 millio ...

Invoke a function from a different vue.js component using the this.$refs property

I'm facing an issue with triggering a sibling element. What I've tried so far <b-img @click="callFileLoader"/> <b-file type="file" ref="fileUploader"></b-file> ... methods:{ callFileLoader () { this.$refs.fileUploader.c ...

Exploring the intricacies of React's useEffect: Solving the challenge of updating data when two separate dependency arrays are

I am facing an issue with two different useEffect hooks where the dependency arrays are different. const [dateFilterSort, setDateFilterSort] = useState({ queryText: initialQueryText(params.sortName), cardText: initialCardText(params.sortName), ...

ways to validate the calling function in jquery

One of the challenges I'm facing is identifying which function is calling a specific error function that is used in multiple places within my code. Is there a method or technique to help determine this? ...

Comparing the Distinctions of jQuery Post and HTML Form Post

After researching extensively, I am still confused about the difference between a Jquery $.post method and submitting an HTML form using post. Here is my code for the jQuery implementation: $.post( "/test", query , function( data ) { console.log(data) ...

Navigating with Google Maps and Its Pointers

I've successfully integrated a JSON array of Marker positions into a Google map. Each marker has an associated infoWindow, which is also functioning as expected. However, I'm encountering an issue where clicking on a marker only displays the in ...

Executing a script within an ASP.NET MVC Project

Currently, I'm in the process of developing a project in MVC that requires using AJAX to fetch XML from an external source. However, I have encountered a challenge where I am unable to directly make the AJAX call due to a XMLHttpRequest same domain po ...

How to display HTML on top without altering the viewport in React?

I am trying to display a component <Top /> above another component <Bottom /> in React. The code structure is as follows: ... [top, setTop] = useState(false); [bottom, setBottom] = useState(true); ... return ( <div> top && (< ...

Custom server not required for optional dynamic routes in NextJS version 9.5.2

I am attempting to implement localized routes with an optional first parameter in the form of /lang?/../../, all without requiring a custom server. Starting from NextJS version 9.5, there is a new dynamic optional parameters feature that can be set up by c ...

What is the best way to incorporate one Div within another Div using JavaScript?

I have a single main div with an id, and I am looking to insert 4 additional child divs inside it. Each of these child divs will then contain 5 more divs each. The code snippet that I currently have is as follows: $( document ).ready(function() { for( ...

How can I align an image and text alongside another image using HTML and CSS?

Having some trouble positioning an Image and Text next to another Image. Check out an example here: I attempted using floats, but it doesn't seem to be working. Here is the code I have: .left {float: left;} .right{float: right;} <div class="left ...