Modifying an image or audio using document.getElementByID("...").src=x+".png" is not effective

I'm having trouble figuring out why it's not working. I've searched online and here, but all I could find were tutorials that didn't include the variable or questions that were too specific.

Can someone help me with this?

<html>
<head>
<title>Test</title>
<script type="text/javascript">

function changeaudio(x);
{

  document.getElementById("audioplayer").src=x+".mp3";
  document.getElementById("image").src=x+".png";
}

</script>
</head>
<body>
<center>
<img id="image" src="1.png">
<audio id="audioplayer" src="1.mp3" controls autoplay loop>
Your browser does not support the audio element.
</audio> 
<br>

<input type="button" id="play" value="Play 1" onclick='changeaudio(1)"' />
<input type="button" id="play2" value="Play 2" onclick='changeaudio(2)"' />
<input type="button" id="play3" value="Play 3" onclick='changeaudio(3)"' />
</center>

</body>
</html>

Answer №1

Be sure to delete the ; at the end of your function definition: function changeaudio(x); should be modified to: function changeaudio(x)

Additionally, correct the syntax for your onclick event: onclick='changeaudio(1)"' should be replaced with: onclick="changeaudio(1)".

Your updated code should resemble the following:

<html>
    <head>
        <title>Test</title>
        <script type="text/javascript">
        function changeaudio(x)
        {
            document.getElementById("audioplayer").src=x+".mp3";
            document.getElementById("image").src=x+".png";
        }
        </script>
    </head>
    <body>
        <center>
            <img id="image" src="1.png" />
            <audio id="audioplayer" src="1.mp3" controls autoplay loop>
                Your browser does not support the audio element.
            </audio> 
            <br />
            <input type="button" id="play" value="Play 1" onclick="changeaudio(1)" />
            <input type="button" id="play2" value="Play 2" onclick="changeaudio(2)" />
            <input type="button" id="play3" value="Play 3" onclick="changeaudio(3)" />
        </center>
    </body>
</html>

jsFiddle Demo

Answer №2

Implementing a jQuery solution:

$(function(){
    $('.play').each(function() {
       var mp3 = $(this).attr("id"); 
        $(this).click(function(){
           $('#audioplayer').attr("src", mp3+".mp3"); 
           $('#image').attr("src", mp3+".png"); 
        });
    });

});

 <center>
            <img id="image" src="1.png" />
            <audio id="audioplayer" src="1.mp3" controls autoplay loop>
            </audio> 
            <br />
            <input type="button" class="play" id="1" value="Play 1" />
            <input type="button" class="play" id="2" value="Play 2"  />
            <input type="button" class="play" id="3" value="Play 3" />
        </center>

Check out the jsFIDDLE DEMO for more

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

Adjust the field of view of the camera in ThreeJS

I'm currently working on adjusting the field of vision for a camera without having to create a new one. So far, I've successfully achieved this for the position using the following code: camera.position.set() Now, I'd like to implement a s ...

What is the Proper Way to Add Inline Comments in JSX Code?

Currently, I am in the process of learning React and I have been experimenting with adding inline comments within JSX. However, when I try to use the regular JavaScript // comments, it leads to a syntax error. Let me share a snippet of my code below: const ...

A function in Jasmine for testing that returns a promise

I have implemented the following function: function getRepo(url) { var repos = {}; if (repos.hasOwnProperty(url)) { return repos[url]; } return $.get(url) .then(repoRetrieved) .fail(failureHandler); function ...

Using AngularJS filters to search through various fields of data

My goal is to conduct a search using multiple fields of a repeating pattern in combination. I am facing an issue where searching by query.$ model does not allow me to search from multiple fields. Specifically, I want to search for the number 1234 along wi ...

Tips for displaying a div only when the input value is greater than 0, and hiding it when the value is 0

My goal is to display a div whenever the input contains at least 1 character and hide it when the input is empty. Despite my efforts, I can't seem to make it work no matter what I try. Here is my initial attempt: var input = document.getElementById( ...

if the arguments for a javascript function are not provided

Currently, I am in the process of learning JavaScript through a book called "Visual Quickstart Guide". However, I have encountered a challenge with understanding the logic behind a particular code snippet. In the function definition below, it appears that ...

Having trouble utilizing Reactjs Pagination to navigate through the data

I'm currently working on implementing pagination for a list of 50 records, but I'm encountering an issue. Even though I have the code below, it only displays 10 records and I'm unaware of how to show the next set of 10 records until all 50 a ...

Is there a way for me to detect when the progress bar finishes and execute a different function afterwards?

After clicking a button in my Javascript function, the button disappears and a progress bar is revealed. How do I trigger another function after a certain amount of time has passed? $('#go').click(function() { console.log("moveProgressBar"); ...

Increase the jQuery Array

After successfully initializing an Array, how can I add items to it? Is it through the push() method that I've heard about? I'm having trouble finding it... ...

I'm currently attempting to incorporate the Material-UI InfoIcon into my code, but I'm unsure of how to properly integrate it within a TextField component

I am attempting to integrate the Material-UI InfoIcon into my TextField code, but I'm unsure of how to go about it. Here is the snippet of Material-UI code: <InfoIcon fontSize="small" /> This is where I would like to place it: <Grid item ...

Ways to determine if an element has exceeded its container's boundaries

After creating the codesandbox, I have developed a webapp that heavily relies on user input. To keep it simple for demonstration purposes, I am displaying various authors on an A4 formatted page using `page` and `font-size` with the `vw` unit for responsiv ...

Ways to trigger an onClick event of one div based on the presence of another div

I'm looking to execute a function when a specific type of button is clicked on my HTML page. I have approximately 10 buttons on the page and I've written the following code to call a function when a button is clicked: $('.divname').ea ...

Issue with React: Reading the 'pathname' property from undefined is not possible

I can't figure out why this error keeps popping up. My goal is to create animated transitions between Routes. Can anyone point out where I went wrong? view image description here I tried reinstalling the react-spring package but it didn't solve t ...

Experience the mesmerizing motion of a D3.js Bar Chart as it ascends from the bottom to the top. Feel free to

Here is the snippet of code I am working with. Please check the link for the output graph demonstration. [Click here to view the output graph demo][1] (The current animation in the output is from top to bottom) I want to animate the bars from Bottom to ...

What is the best way to capture GotError [HTTPError]: When the response code 404 (Not Found) occurs in a nodejs

If the URL provided is incorrect and the Got module raises a HTTPError, how can I properly catch the error? Using try-catch does not seem to be effective in this situation. const got = require('got'); got(`https://www.wrongurl.com`) ...

Do you have to host a node server to run Angular applications?

(say) I am currently working on a project that utilizes Laravel or PHP for the back-end and Angular for the front-end. In my setup, I am using angular.js files from a CDN, which should work fine. However, I find myself confused when tutorials and books me ...

Communicating JSON data through AJAX with a WCF web service

Hey everyone, I could really use some assistance with my current coding issue. My goal is to pass the value 2767994111 to my WCF web service using jQuery AJAX. var parameter = { value: "2767994111" }; $('#btSubmit').click(function () { $ ...

The jQuery onClick function functions effectively for the initial two clicks; however, it ceases to

I am currently experimenting with jQuery to dynamically load a specific div from another page on my server into a designated section on the existing page. While the code is successfully functioning for the first two clicks on the website, it fails to work ...

Identifying when a user is idle on the browser

My current project involves developing an internal business application that requires tracking the time spent by users on a specific task. While users may access additional pages or documents for information while filling out a form, accurately monitoring ...

Issue encountered when AngularJS struggles to evaluate regular expression within ng-pattern

Currently, I am implementing the ng-pattern argument in an input text field to restrict input to only numeric values: <input type="text" ng-model="numericField" ng-pattern="/^[0-9]*$/" /> However, there seems to be an unusual behavior in the regex ...