Button press triggers the fadeIn function successfully, but the keypress event does not have the same effect

I'm currently facing an issue with two div elements on my webpage. I want only one of them to be visible at a time, depending on which key is pressed. If the 1 key is pressed, I want 'div1' to fadeIn (if it's not already visible) and for 'div2' to fadeOut. On the other hand, if the 2 key is pressed, 'div2' should fadeIn while 'div1' fades out. Below is the code snippet that I have implemented.

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#div2").fadeOut();
});
</script>
<script>
$(document).ready(function(){
    $(document).keydown(function(e){
        if (e.keyCode==49)
            $("#div2").fadeOut();
            $("#div1").fadeIn();
    });
    if (e.keyCode==50)
        $("#div1").fadeOut();
        $("#div2").fadeIn();
    });
});
</script>
</head>
<body>
<h1>To toggle visibility, press 1 or 2 keys - 'div1': 1 & 'div2': 2</h1>
<div id="div1">1</div>
<div id="div2">2</div>
</body>
</html>

While this functionality worked well with buttons, it seems to encounter issues when using keypresses. Can anyone help me figure out what mistake I am making?

Answer №1

Make sure to pay attention to the syntax and watch the console for any errors that may arise while running your code, as a syntax error could occur.

$(document).ready(function(){
    $("#div2").fadeOut();
    $(document).keydown(function(e){
      if (e.keyCode==49){
        $("#div2").fadeOut();
        $("#div1").fadeIn();
      }
      if (e.keyCode==50){
        $("#div1").fadeOut();
        $("#div2").fadeIn();
      }
    });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<h1>Fade in div1 by pressing the 1 key.  Fade out div1 and fade in div 2 by pressing the 2 key.</h1>
<div id="div1">1</div>
<div id="div2">2</div>

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

Generate a new array using a single value extracted from an existing array

I'm new to working with arrays. Before this, I used to manually code everything in HTML. My question is, can you create an array based on the values of another array? var pmmain =["aaa", "bbb", "ccc", "ddd", "eee", "fff", "ggg", "hhh", "iii", "jjj", ...

Acquiring the value of jQuery for utilization in PHP

Below is the code I am working with: $('#topic').on('change', function() { var sel = $(this).find('option:selected').text(); $.ajax({ type: 'post', dataType: 'text', url: ...

Unable to include the variable "$localStorage"

While working on my method in app.js, I encountered the following error: Uncaught Error: [$injector:strictdi] function($rootScope, $q, $localStorage, $location) is not using explicit annotation and cannot be invoked in strict mode http://errors.angula ...

Creating vibrant squares using HTML and CSS

My objective is to incorporate 3 input options for selecting the color, size, and amount of cubes. The image below showcases my peer's final project, but unfortunately, he refused to share the code with me. We were given a basic template to begin with ...

When using jQuery's POST method, the "done" event is triggered, however, no data is being sent

I've been working on implementing AJAX form submission and wrote a function to handle it when the button is clicked: function putUser() { $('button#putUser').on('click', function() { var user = $('input#user' ...

Tips for sorting through various elements or items

How can I improve my filtering function to select multiple items simultaneously, such as fruits and animals, or even 3+ items? Currently, it only allows selecting one item at a time. I attempted using , but it had bugs that displayed the text incorrectly. ...

How to use Laravel to upload images using Ajax

My database table structure for users is as follows: id (integer) firstname (string) lastName (string) email (string) login (string) password (string) image (text) I want to be able to insert an image along with the user data using Ajax and jQuery. How ...

The email validation UI dialog is failing to display any dialog

<html> <head> <link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"> <script src="//code.jquery.com/jquery-1.10.2.js"></script> <script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"& ...

Challenges with handling callbacks in Javascript

I'm currently working on creating a user-friendly GUI using the w2ui library, but I've encountered an issue with integrating a toolbar into my main layout. The problem arises when the toolbar is added before the layout is fully constructed. Sinc ...

There seems to be an issue with your SQL syntax that is preventing the data from being entered correctly into the database using Node.js, MySQL, and Express

After successfully displaying data from my database, I attempted to add data to it using the following code snippet: exports.tambahData = (req, res) => { var keyy = req.body.keyy; var valuee = req.body.valuee; var brand = req.body.brand; ...

Can JavaScript be adapted to simulate the features of an object-oriented programming language?

Is there a method in Javascript to imitate an object-oriented language? For example, is it possible to replicate the ability to define custom classes/objects with properties? Given that JSON serves as a means for passing objects in JavaScript, I assume the ...

Efficiently transmitting WebSockets events/messages to multiple controllers in AngularJS

Incorporating AngularJs, I created a factory to manage a WebSocket connection effectively. Here is the code: .factory('WebSocketConnection', function () { var service = {}; service.callbacks = []; service.connect = func ...

How can we prevent the text from shifting when the border width is adjusted

I've run into an irritating issue. My left menu text keeps shifting when I expand the border using jQuery. I've tried various solutions to prevent the text from moving, but nothing seems to work. Any suggestions? Could it be a CSS problem with t ...

After the "div" tag comes the magic of AJAX, PHP, and JAVASCRIPT, replacing

My Ajax implementation is successfully displaying the selected content on a div, but unfortunately, everything that comes after the div is getting replaced by this output. I am unsure of why this is happening and how to resolve it. If you have any insigh ...

Positioning of buttons within a div

I am currently designing an inspiration post style: https://i.stack.imgur.com/I5J0H.png However, I am encountering some challenges while creating it: The buttons are not rounded when the window size is changed Social icons are not being displayed I am ...

When scrolling through a page, the MySQL data being loaded via an ajax/jquery call is not displaying the accurate information

Currently, I am facing an issue with loading data from a MySQL database onto a webpage using AJAX/jQuery call. The problem lies in receiving duplicate data that has already been fetched and displayed on the page. I believe there is nothing wrong with the s ...

IE compatibility problem with the alignment of input group buttons and textboxes in Bootstrap v4

Encountering an issue with input group in IE while using bootstrap v4, working fine in Chrome. Specifically using IE 11 Here is my plunkr: input group bootstrap v4 Chrome display: https://i.sstatic.net/yXtEW.png IE display: https://i.sstatic.net/WiRz ...

Arranging images effortlessly using jQuery sortable feature in HTML

I'm currently working on creating sortable images using jQuery in an HTML document. I've encountered an issue with the source code here. I have implemented the jQuery sortable function in a functions.js file and successfully tested it on another ...

The difference between importing CSS in JavaScript and importing it directly in CSS lies in the way

Hello there, I am just starting out with web development and learning about Vue.js. In Vue 3, the recommended way to import CSS files from different packages is as follows: Method 1: Import directly in app.js //app.js import '../css/app.css'; i ...

Adjusting the size of FontAwesome symbols using FitText

I recently started using FitText () to dynamically resize certain titles on my webpage. While I've had success with resizing h1, h2, and other text elements, I've run into an issue when trying to apply it to fontawesome icons. I know that FitText ...