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

When invoked, a Javascript Object comes back empty

My code snippet: const channels = fauna.paginate(q.Match(q.Index("channels"), "true")) // Query FaunaDB database for channel list => create constant called users containing results const channelList = channels.each(function (page) { ...

Aligning a div in relation to the background image

I am seeking guidance on how to center a Div Box and make it responsive relative to the background image. The div box should be contained within the white box, similar to the example shown here: body{ font-family: 'Roboto Mono', monospace; ...

Insert a division into the table following every row

I'm working with a table that can be found here: https://codepen.io/anon/pen/bjvwOx Whenever I click on a row (for example, the 1st row 'NODE ID 1'), I want the div with the id #divTemplate to appear below that particular row, just like it d ...

Include a <div> element to display the date in an HTML format, ensuring that the days and months

I am working on a project where I have a list of dates and I need to format them by adding div tags to separate the days, months, and years into different divisions. <div class="campaign">30/11/2016 - <a href="#" target="_blank">Dummy Text& ...

How come a colon within a function's body does not result in an error in JavaScript?

During my coding journey, I encountered a situation where I was attempting to return an object from an arrow function. However, I noticed that the code snippet below was simply returning undefined. After some investigation, I determined that the curly br ...

Avoiding the creation of a history entry while switching languages on a Next.js website

I'm currently developing a Next.js project that includes a language dropdown feature for users to choose their preferred language. In the existing setup, we are utilizing the router.push method from next/router to update the language selection and red ...

How can text be concealed within an input field?

My degrees converter code is functioning well, but I have an issue. When I input a number for one temperature type, the conversion for the other two types is displayed correctly. However, if I then enter a number for another temperature type, the previous ...

The Javascript query is returning an [object Object] data type

I am facing an issue with a JavaScript file that is querying a SharePoint list. Specifically, the Priority drop down in the query result is displaying as [object OBJECT]. I suspect it has something to do with the var query string where I have added the &ap ...

error being triggered due to relative positioning

On my webpage, I have a set of buttons located at the bottom. When I first open the page, all the buttons are displayed properly. However, sometimes the first three buttons become hidden mysteriously and the layout changes. I am puzzled as to what could be ...

Utilizing the ref received from the Composition API within the Options API

My current approach involves utilizing a setup() method to bring in an external component that exclusively supports the Options API. Once I have imported this component, I need to set it up using the Options API data. The challenge I face is accessing the ...

Problem arising from animation not commencing at expected starting point

Creating a feature on an app that involves breathing exercises using CSS animations. The challenge I'm facing is ensuring the words "exhale" and "inhale" appear synchronously with the animation of a circle shrinking and enlarging. However, the animati ...

Div element positioned outside of another div element

I hate to bug you with more css issues, but I'm really struggling with this one. The problem I'm facing is that a sub div is overflowing the boundaries of its parent div. I tried using: display: inline-block;` but then the outer div goes haywir ...

Issue with multiple dropdown menus not closing when clicked on

The current implementation provides the functionality to convert select boxes into list items for styling purposes. However, a drawback of the current setup is that once a dropdown is opened, it can only be closed by clicking on the document or another dr ...

The qTip comment box vanishes when focused on by IE/Edge browsers using touch devices

A unique JavaScript library called qTip is being utilized in my project. The application includes a StarRating and Comments feature, both of which are enabled by this plugin. After selecting a rating using the stars, users have the option to add comments, ...

Developing a customized WordPress walker to specifically target the first and last links

I've implemented a custom walker in my Wordpress site: class Custom_Walker_Nav_Menu extends Walker_Nav_Menu { function start_el(&$output, $item, $depth = 0, $args = array(), $id = 0) { if ( $depth ) $indent = str_repeat("& ...

Best practices for sending variables to an HTML page using nodemailer

I am interested in sending an email with an HTML template that includes dynamic data. For example, I want to include a unique id within a link on the page. Is it possible to insert dynamic data into HTML content when sending emails? If yes, I would apprec ...

I am seeking to modify the CSS of the parent component upon the loading of the child component in Angular

In my Angular blog, I have a root component with a navigation bar containing router links to create a single-page application. My goal is to darken the background around the link when the child component loads. Currently, the link highlights only when pres ...

What is the most creative way you can think of to create a CSS/JS animated

Is using an animated SVG the best way to create these wavy blobs for mobile compatibility? What approach would you take? Here is a similar example I found var wave = document.createElement("div"); wave.className += " wave"; docFrag.appendChil ...

The end of the /if in the small template system fails to correctly detect the desired condition

If I write the following line on its own, he cuts it without any reason. So...: Greetings, I'm in need of assistance regarding an issue that is currently beyond my understanding. I'm facing a challenge with a small TPL-System which requires so ...

What is the best way to extract additional values linked to the query within the array?

I have successfully retrieved all subcategories of a category using the code below. However, I am now facing an issue where I also want to fetch other fields associated with each subcategory, such as the price if the subcategory is a Product like Smartphon ...