Generating a transient image upon a key press event using JavaScript

I'm currently working on a personal website as a fun project, and I had the idea of adding an easter egg feature where if a user presses the letter "e" anywhere on the site, a small image of a speech balloon will briefly appear and then disappear. Ideally, it would also make a sound or randomly appear on different parts of the page, but my main goal right now is just to get it functioning properly. Unfortunately, I don't have much experience with JavaScript.

I've been doing some research and found examples of displaying an image when clicked, as well as translating key presses into click events, but I'm having trouble putting everything together correctly. I've tried several methods but haven't had any success so far. I've even looked into scripts that create images when clicked, but I'm not sure how to adapt that to a key press event.

Here is what I have managed to come up with so far. From my understanding, I've set up an event listener to detect when the "E" key is pressed, and then it should call the showImage function to change the display property of the div from 'none' to 'block'. However, when I press the "E" key, nothing happens.

<script>
var addEvent = document.addEventListener ? function(target,type,action){
    if(target){
        target.addEventListener(type,action,false);
    }
} : function(target,type,action){
    if(target){
        target.attachEvent('on' + type,action,false);
    }
}

addEvent(document,'keydown',function(e){
    e = e || window.event;
    var key = e.which || e.keyCode;
    if(key===101){
        showImage();
    }
});

const showImage = () => {
        document.getElementById("first").style.display ='block';
    }
</script>

<body>
<div id="first" style="height:400px; width:400px; display:none;">
    <img src="test.png"> 
</div>
</body>

Answer №1

To begin, let's implement an appropriate event handler by adding the necessary code. The current code contains outdated workarounds that are no longer required. Consider using a simpler approach like this:

document.addEventListener('keydown', e => {
  console.log(e);
});

Afterwards, check your browser's developer console, navigate back to the page, and try typing a key to view keyboard events on the console.

We will now create a hidden element on the page featuring both an image and audio:

<div class="hidden" data-key-code="KeyE">
  <img src="https://i0.wp.com/acegif.com/wp-content/gif/confetti-40.gif" />
  <audio src="https://actions.google.com/sounds/v1/crowds/female_crowd_celebration.ogg" />
</div>

In your CSS, include a utility rule:

.hidden {
  display: none;
}

Upon page load, the hidden element will not be visible due to the display: none property. Continuing with JavaScript for handling keyboard events.

The HTML includes a data attribute for the key code allowing easy modification in the future without altering the JavaScript. You can add multiple elements on the page without requiring script changes. Here is our script:

document.addEventListener('keydown', e => {
  // Obtain the desired element, if present.
  const el = document.querySelector(`[data-key-code="${e.code}"]`);

  // If element not found, do nothing.
  if (!el) {
    return;
  }

  // Toggle visibility of the element
  el.classList.toggle('hidden');

  // If element is hidden, pause the audio; otherwise, play it.
  el.querySelector('audio')[
    el.matches('.hidden') ? 'pause' : 'play'
  ]();
});

Test a live example here: https://jsfiddle.net/fqaogu59/

Answer №2

To display an image after a key press event, you can use the following method:

// Trigger the event
document.addEventListener("keyup", (event)=>{
// Check if the pressed key matches the desired key
  if (event.key == "e")
  {
    // Select the image element
    const img = document.querySelector("#your_img");

    // Change the display property to show the image
    img.style.display = "initial";
  }
});

It's important to note that accessing the image directly upon key press may not be optimal, as it involves querying the DOM each time. However, in the case of an easter egg like this where the key is unlikely to be pressed multiple times, the current approach should suffice.

Answer №3

It seems like the code snippet provided is implementing a function called showImage that displays an element with the id "first" when the key "E" is pressed. Additionally, there is an event listener listening for keyup events and calling the showImage function when the key pressed is "E".

<script>

     const displayOnKeyPress = () => {
        document.getElementById("first").style.display ='block';
    }
    // Function to be triggered on key press
    function handleKeyPressed(event) {
        // Check if the pressed key is "E"
        if (event.key === "E") {
            displayOnKeyPress();
        }
    }

    // Add event listener for the 'keyup' event
    document.addEventListener("keyup", handleKeyPressed);
</script>

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

How come JavaScript code seems to run the second part on occasion?

When working with drawing background on a canvas and adding small images on top of that background, I sometimes encounter an issue where the background is drawn over the small images. This behavior puzzles me. Can you shed some light on why this might be h ...

MVC3 does not support JQuery UI

Just recently, I had all my jquery-ui elements functioning perfectly. However, now it seems that none of the jquery-ui features are working anymore. In my Site.Master page, I have included the following code... <link href="../../Content/Site.css" rel=" ...

Tips for resolving table header issues and enabling vertical movement of data while simultaneously allowing both the header and data to move vertically

I need assistance with a challenge I am facing. I have created a table using HTML tags, and now I want to add a vertical scrollbar to the browser without affecting the table's header. The data in the table should move when the vertical scrollbar is us ...

Utilizing the Angular Date pipe alongside a straightforward timer powered by Moment.js

I'm encountering an issue with the following code that is designed to calculate the difference in milliseconds between two dates. This script is intended to track the elapsed time since a view was opened: this.timer.start = new Date(); this.tim ...

Utilizing multiple conditions in MongoDB is a great way to filter results when a specific key

const filterCriteria = { carColor: req.query.carColor, languages: { $regex: `${req.query.languages}`, $options: 'i' }, incomeMonth: { $gte: req.query.incomeMonth }, incomeYear: { $gte: req.query.incomeYear }, ...

Tips for inserting JSON information in JavaScript

I am working with a JSON file that contains data in the following format: { "rigidBodies": [ { "name": "ball1.png", "imagePath": "ball1.png", "origin": {"x": 0, "y": 0}, "polygons": [ [ ...

Is there a way to set the default state of a checkbox in a spring-form?

I have set up my web content using spring-boot with .jsp files. The controller code is as follows: @Slf4j @Controller @AllArgsConstructor @SessionAttributes({"language", "amount", "words"}) public class LanguageController { private LanguageService lang ...

Encountering difficulty in adding content to a table using JavaScript. An error message appears stating that assignment to a function

I am utilizing ajax to retrieve an item from a web API, and then attempting to allocate attributes of that item to a table: function find() { var id = $('#contentID').val(); $.getJSON(uri + '/' + id) .done( ...

What is the best way to ensure that the auth variable remains unchanged throughout the program, even after re-rendering, using useRef or a different method?

Is there a way to utilize this code with function-based components and hooks instead of class components? import React, { useEffect, useState } from 'react'; const GoogleAuth = () => { const [ isSignedIn, setIsSignedIn ] = useState(null); ...

Utilize a node module within a web browser

Currently, I am utilizing the straightforward Refify npm module to manage circular structure JSON. It performs the task of stringifying a circular structure JSON object in Node.js for transmission to the client. Upon receiving the stringified JSON in my An ...

Tips on using MUI Texfield and Redux to update state

I am facing an issue with my input field as I attempt to pass some information before navigating to a different page. The problem lies in the fact that my Redux state is not updating, although the console confirms that the value is being passed correctly. ...

What is the process for indicating an option as "chosen" within Embedded JavaScript Templating (EJS)?

I've been working on a function that allows users to modify each other's data, including the ability to change roles. I'm having trouble getting the select form to display the current role of a user with the "selected" attribute. This is wh ...

An unexpected error occurred in React.js when trying to use WebRTC RTCPeerConnection.addStream function, indicating

I'm trying to create a basic video chat using react.js and WebRTC. However, I'm encountering an error on line pc.addStream(localStream): TypeError: Argument 1 of RTCPeerConnection.addStream is not an object. Additionally, I can't seem to ...

The Transition Division Is Malfunctioning

I've encountered an issue where I am trying to move a div by adjusting its left property, but no transition is taking place. Regardless of the changes I make to my code, the result remains the same. Below is the current state of the code. Can anyone i ...

How to implement the ECharts animated bar chart in Angular version 16?

The animated bar chart in ECharts functions perfectly on Stackblitz. You can check it out here in the Stackblitz Angular 16 demo. However, attempting to run the same demo in a local Angular 16 project led to the following errors. Error: src/app/animated- ...

I am experiencing difficulty with the Click() operation in Selenium web driver as it is not successfully redirecting me to another page

Hello everyone, I could really use your assistance with a problem I'm facing. WebElement wb=driver.findElement(By.name("NavHeader1$tabs$ctl00$btnNavHeaderTab")); Actions act=new Actions(driver); act.moveToElement(wb).perform(); ...

Displaying XML data using d3js

Currently, I am working on a d3.js assignment for my school project. While looking at some examples to load an XML file, I seem to be encountering difficulties in figuring out what's going wrong. The XML file is loading correctly, but as I am still le ...

Security at risk - watermark.js

I have been utilizing watermark.js to protect images on my WordPress website. During testing, I encountered an error in img.src = gcanvas.toDataURL();. Despite my efforts, I have not been able to locate where this value should be set. Here is the code th ...

Find a specific string within an array where both the keys and values are subject to change

Below is an array that I have: var Array = [{id:100,name:'N1',state:'delhi',country:'india',status:'active'}, {id:101,name:'N2',state:'kenya',country:'africa',status:'suspended&a ...

Creating interconnected select boxes based on JSON data to display parent-child relationships in a cascading manner

A dynamic creation of chained select-boxes has been implemented based on JSON data fetched from the server. In this cascading process, each select-box is an object with specific properties: Parent Attribute: The name of the parent object for the current ...