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

The data in ag Grid does not display until all grid events have been completed

After setting the rowData in the onGridReady function, I noticed that the data does not display until all events are completed. I also attempted using the firstCellrendered event, but unfortunately, it did not resolve the issue. OnGridReady(){ this.r ...

Linking together or organizing numerous JavaScript function executions in instances where the sequence of actions is crucial

I have implemented a web api method that conducts calculations by using a json object posted to the method. I believe that a jquery post is asynchronous. Assuming this, I want to be able to link multiple calls to the js function invoking this api method in ...

Creating a proper nth-child CSS for multi-level HTML elements involves understanding the structure of the elements

My current project involves a screen where widgets can be dynamically inserted into the DOM. I am looking to adjust the z-index based on the number of times the class decrement-z-index appears. This is the CSS code I have written in an attempt to achieve ...

There appears to be no data available from the Apollo Query

I'm facing an issue with the returned data from Apollo Query, which is showing as undefined. In my code snippet in Next.js, I have a component called Image with the src value set to launch.ships[0].image. However, when running the code, I encounter a ...

Integration of Unlayer EmailEditor into React causes fatal errors in the application

I am attempting to integrate Unlayer into my React Application by using this guide: https://github.com/unlayer/react-email-editor. I have configured Webpack for this purpose. However, when I try to import EmailEditor in one of my modules: import React fr ...

What could be causing the error with firebase Sign In in next.js?

I set up a sign in page to enter email and password for Firebase authentication. The sign up process works fine, but I'm encountering an issue with the sign in functionality. 'use client' import { useState } from 'react'; import { ...

What's the best way to search through various addresses for the source in an image tag?

In my current Laravel 5.8 project, I am faced with the task of searching through three different image sources for an img tag. First, I attempt to load the image from "". If that fails, I try a second URL like "". Should both attempts be unsuccessful, I th ...

What could be the reason my bootstrap cards are stacking vertically instead of being placed horizontally next to each other?

My Bootstrap cards are not aligning side by side and I'm having trouble locating the error in my code. I'm working with Django and HTML. {% extends 'base.html' %} <div> {% block content %} <h1>Team Members<h1& ...

Encountering issues with managing CometD channels within Angular 2

After dabbling in Angular2 and Typescript, I decided to challenge myself by creating an application using plain javascript with the CometD library. The goal of this app was to retrieve data from a CometD channel and present it to the user in some way. So, ...

Utilizing the Vue feature of dynamic route naming within a component's function

Currently, I am working on creating a dynamic view rendering using Vue and Laravel. However, I am facing difficulty in understanding how to pass the dynamic parameter to the component function. Router.map({ '/cms-admin/:page': { comp ...

Utilizing ThreeJS to Implement Targeted Bloom Effects on Individual Object Components with Emission Mapping

I have a project where I need to showcase 3D objects with small LED lights that should emit a glow effect. I've attempted to use UnrealBloom, but the issue is that it affects the entire scene and makes everything look blurry, not just the parts with t ...

What is the best method to activate or deactivate a link with jQuery?

Can you provide guidance on how to toggle the activation of an anchor element using jQuery? ...

Exploring the world of handling GET and POST parameters in Node.js with

As someone who is new to Node/Express, I've noticed that GET parameters can be captured using the following syntax: app.get('/log/:name', api.logfunc); For POST requests, it can be done like this: app.post('/log', ... (with for ...

Create a customized menu with jQuery that disappears when hovered over

Check out this menu I've created: http://jsbin.com/useqa4/3 The hover effect seems to be working fine, but I'm looking to hide the div #submenuSolutions when the user's cursor is not on the "Solution" item or the submenu. Is there a way to ...

Creating JSON with PHP: Ensuring consistent keys in JSON output derived from PHP arrays

Is there a method to convert a PHP array (or any other similar PHP object) into JSON while maintaining identical keys for a JSON array? For example: {"categories" : [ {"key": "data1"}, {"key": "data2"}, {"key": "data3" } ] } It is worth noting that the ...

I provided Array.Filter with a function instead of a predicate, and surprisingly it gave back the entire array. How is that possible?

I encountered an unusual scenario where I passed a function instead of a predicate to Array.filter. This function modified individual student objects and the filter returned the whole array. This led me to question, why is this happening? According to co ...

What is the best way to declare a global variable while making an asynchronous call using AngularJS?

Is there a way to utilize the single_video variable outside of the controller function? The issue arises when attempting to access it in the second console.log, as it returns an 'undefined' error due to asynchronousity despite successfully printi ...

Issue encountered when assigning a new value to a private class property at a global scope in JavaScript

I am encountering an issue in my code where I define a private class member using "#", initialize it in the constructor, and then receive an error when attempting to set/access the value. Uncaught TypeError: Cannot read private member #mouse from an object ...

Switching from the jQuery .it() function to the Angular framework

I am looking to convert this code to Angular. I have already written some of the code, but I am unsure what to use in place of :It(). The jQuery code can be found at the following URL: jsfiddle.net Here is my Angular code: x = 3; $scope.itemsPerPage = 3; ...

Combining the Powers of Angular JS and Symfony2

Currently working on a project involving Symfony2 and in need of some advice. Considering a hybrid application approach in two ways: a) Using a traditional form with CSRF Token for the Login Page handled by Symfony2, and b) Inner pages (potentially module ...