Surprising outcomes encountered when playing audio with JavaScript

https://i.sstatic.net/1jz45.png

I've been diving into learning JavaScript and decided to create a simple web page. This page, when Pikachu (image) is clicked, plays an audio file.

Similarly, if the string "Pikachu" is typed into the form, it should play the same sound, otherwise, it should display "not found".

Here's the HTML code I have:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>Pokemon Cries</title>
        <link rel="stylesheet" href="style.css">
        <script type="text/javascript" src="sounds.js"></script>
    </head>
    <body>
        <form>
            <input id="inputform" type="text" name="search">
            <button onclick="getdata()">Search</button>
        </form>
        <img class="images" src="images/pikachu.png" alt="Pikachu" onclick="pikachusound()">
    </body>
</html>

My JavaScript code looks like this:

var pikachu=new Audio("sounds/pikachu.mp3");

var inputstring;

function getdata()
{
    inputstring=document.getElementById("inputform").value;
    if(inputstring.toLowerCase()=="pikachu")
    {
        pikachusound();
    }
    else
    {
        alert("Not found");
    }
}
function pikachusound()
{
    pikachu.play();
}

And here's my CSS snippet:

body{
   margin: 0;
   padding: 0;
}
.images{
    height: 150px;
    width: 150px;
    margin: 20px;
    border-style: solid;
    border-radius: 50%;
    border-width: 5px;
    border-color: grey;
}

Clicking on the image works perfectly fine, but sometimes when I input "Pikachu" in the form, the sound doesn't play as expected. I've searched extensively online but can't seem to pinpoint the cause of this erratic behavior.

If anyone could help me identify the bug, I would greatly appreciate it. Thank you!

Answer №1

It's challenging to determine the issue definitively since you mentioned that it works "sometimes" and doesn't work "other times." One possible reason could be related to the use of a form with a submit button (which is the default type when no type attribute is specified). Upon submission of the form (initiated by clicking the submit button), the page gets redirected, potentially interrupting other code execution on the page. This creates a race condition between the execution of getData() and the form submission, leading to inconsistent outcomes.

I recommend reconsidering the necessity of using a form in this scenario, especially if there is no actual data submission occurring.

Your coding practices also seem outdated. Below is an updated version of the code along with some explanatory comments:

var pikachu= new Audio("sounds/pikachu.mp3");
    
// Obtain a reference to the input element once instead of repeatedly
// fetching it every time the function runs. Also, store the element 
// itself rather than its property value for easier accessibility.
var inputElement = document.getElementById("inputform");
var imageElement = document.querySelector("img[alt='Pikachu']");
var buttonElement = document.querySelector("button[type='button']");

// Avoid using inline event handlers like "onclick" in HTML; utilize 
// modern standards by binding events in JavaScript
buttonElement.addEventListener("click", getdata);
imageElement.addEventListener("click", pikachusound);

function getdata() {
   if(inputElement.value.toLowerCase() == "pikachu") {
      pikachusound();
   } else {
      alert("Not found");
   }
}

function pikachusound(){
  console.log("Sound playing!");
  pikachu.play();
}
body{
       margin: 0;
       padding: 0;
}
   
.images{
   height: 150px;
   width: 150px;
   margin: 20px;
   border: 5px solid grey;
   border-radius: 50%;
}
<input id="inputform" type="text" name="search">
<!-- To get a regular button, specify the type -->
<button type="button">Search</button>

<img class="images" src="images/pikachu.png" alt="Pikachu">

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

Exploring Objects without the need for loops

Currently, I am focusing on optimizing the performance of the following objects: var scheduleFee = { poor = {level1:25,level2:25,level3:25} , good = {level1:15,level2:20,level3:25} , vgood = {level1:10,le ...

Encountering ERR_EMPTY_RESPONSE when using the $.POST method

I have been struggling with a issue on my social networking site that includes chat functionality. I have utilized the $.post method extensively across multiple pages, and it generally functions well except for a specific page called message.php where user ...

Move to Fieldset Upon Link Click

Here's an example of what I have implemented so far here It's evident that this is not fully functional due to the PHP and jQuery integration. This demo is just a showcase of my progress. I am looking to create a functionality where clicking on ...

`How can I extract HTMLElements from slots in vue3?`

When attempting to develop a Layer component, I encountered some challenges. Here is the code: // Wrapper.vue <template> <slot v-bind="attrs"></slot> </template> <script lang="ts" setup> import { defi ...

Adjust the x and y coordinates of the canvas renderer

Manipulating the dimensions of the canvas renderer in Three.js is straightforward: renderer = new THREE.CanvasRenderer(); renderer.setSize( 500, 300 ); However, adjusting the position of the object along the x and y axes seems more challenging. I've ...

Guide for populating the chosen item in a combobox when the form control option has various parameters

I need help populating the selected saved item into the form control. <select class="form-control"> <option data-parameter-id="685" data-parent-id="1052" data-aggregation-id="null" data-aggregation-parameter="null">ABC</option> & ...

Can VueJS Computed handle multiple filters at once?

I am encountering an issue with this code - when I attempt to add another filter inside the computed section, it doesn't work. However, if I remove the additional filter, the code functions correctly. My goal is to have both company and product searc ...

What is the best way to send a JSON Object containing option parameters in order to open a new window?

Have you noticed the interesting parameter list for the window.open() object? Is there a possibility to use window.open({options..}); instead? What are your thoughts on this matter? ...

Prevent clicking on form until setInterval has been cleared using React useEffect

Here is a link to a sandbox replicating the behavior: sandbox demo I have integrated a hook in a React component to act as a countdown for answering a question. React.useEffect(() => { const timer = setInterval(() => { setTimeLeft((n ...

Utilize the atan2() function to rotate a div so that it follows the movement of the mouse

I am trying to create an effect where the mouse aligns with the top of a div and the div rotates as the mouse moves. The rotation should happen when the top part of the div is in line with the mouse cursor. My goal is to achieve this using the atan2 functi ...

Obtaining documents through Mojolicious

Just a quick inquiry - I have successfully generated a .doc file using my mojolicious app with the help of the CPAN module MsOffice::Word::HTML::Writer. Now, the challenge I'm facing is figuring out how to make the browser initiate the download proces ...

Which is Better for Creating DropDown Menus: CSS or JavaScript?

Starting a new project that involves dropdown menus with categories and subcategories within them. I'm curious about the advantages of using CSS3 only menus compared to traditional JavaScript ones. There are several jQuery menu options available as we ...

Reactjs rendering problem related to webpack

Greetings! I am new to using react js and decided to create a quiz application. However, I encountered an error when the render function was called. Below is my webpack.config file: module.exports = { entry: { app: './src/index.js' }, ...

Video margins within a webview

After numerous attempts to embed a YouTube video in a WebView, I'm still struggling with a persistent small margin on the right side of the video. I've researched similar issues and attempted to address it through JavaScript adjustments without ...

ALSO, various criteria

function findLogicalAND(){ let result; let index; for (index = 0; index < arguments.length; index++){ result = arguments[index] && arguments[index+1]; } return result; } console.log(findLogicalAND(true, true, false, false)); I want to r ...

"What are the reasons for encountering a '404 not found' error with Django when accessing a

I recently developed a Django script that utilizes a Python parser to navigate the web. I have set up AJAX to send requests to this Django script, but I am encountering a 404 error for the URL when the Ajax runs. Can you help me understand why this is occu ...

Create a duplicate of a div element, including all of its nested elements and associated events, using

Attempting to duplicate a div containing input fields but the event listeners are not functioning. Despite performing a deep copy in the following manner - let rows = document.querySelectorAll('.row'); let dupNode = rows[0].cloneNode(true); sh ...

Require assistance in generating three replicas of an object rather than references as it currently operates

I am encountering an issue with my code where I seem to be creating 4 references to the same object instead of 4 unique objects. When I modify a value in groupDataArrays, the same value gets updated in groupDataArraysOfficial, groupDataArraysValid, and gro ...

Creating a dynamic select functionality in Drupal forms

Being more focused on backend development, I am facing a challenge that may be simple for jQuery experts. In Drupal, I have two arrays - one containing names of views and the other having displays for each view. To populate these arrays, here is the code s ...

Issue with MaterialUI value prop not updating after dynamic rendering of components when value state changes

As I dynamically generate Material UI form components, I encounter an issue with updating their values. The value prop is assigned to a useState values object, and when I update this object and the state, the value in the object changes correctly but the M ...