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

Creating numerous duplicates of a highly nested immutable Object can be done by using a combination of spread operators

I am currently working on retrieving data from firebase/firestore using Javascript. I have created a function where I retrieve my products collection and pass this data to the React state.products by utilizing the setState() method. My objective is to tra ...

Incorporate a stylish gradient background into react-chartjs-2

I am currently working on adding a gradient background with some transparency to a radar graph within a react component. So far, I have only found solutions that involve referencing a chartjs canvas in an html file, but none for implementing it directly in ...

Is there a way to trigger a function for both a left and middle click at the same time?

Check out this code snippet: $('a').on('click', function(){ myfunc($(this)); }); function myfunc(el){ console.log('Either left or middle click clicked on the link'); } a{ cursor: pointer; } <script src="https://aj ...

Is there a way to effectively incorporate react-native with php and ensure that the data returned by the fetch function is

I'm struggling to make my return value work in this code. Has anyone had success using react-native with php and fetch json? Any tips or advice would be greatly appreciated. PHP $myArray = array(); $myArray['lat'] = $_POST['lat']; ...

Enter key always causes the Bootstrap form to submit

I am working with a jquery function: $("#get-input").keyup(function (event) { if (event.keyCode === 13) { $("#get-data").click(); } }); $("#get-data").click(function (e) { var endpoint = $(".get-input").val(); if ($('#data-d ...

Guide to setting up a datePicker in a cellEditorSelector

In my grid, I want to have different editors for different rows within the same column. The ag-Grid documentation provides information on how to achieve this using colDef.cellEditorSelector as a function: link I have successfully created unique editors fo ...

Using Jquery to insert an if statement within the .html element

Trying to implement jQuery to replace html content within an object, but struggling with incorporating an if statement. Like this: $(this).html("<select id=\'status\' name=\'status[]\' multiple><option valu ...

Switch the visibility of a div tag using Next.js

Script export default function Navigation(){ let displayMenu = false; function toggleMenu() { displayMenu = !displayMenu; } return ( <> <button onClick={toggleMenu}>Toggle Navigation</button> {/*This code sh ...

Unable to abort AWS Amplify's REST (POST) request in a React application

Here is a code snippet that creates a POST request using the aws amplify api. I've stored the API.post promise in a variable called promiseToCancel, and when the cancel button is clicked, the cancelRequest() function is called. The promiseToCancel va ...

Troubles with AJAX and jQuery

<html> <head> <title>Ajax Example</title> <script type="text/JavaScript" src="jquery-1.5.1.min.js"></script> <script type="text/JavaScript"> function fetchData() { $.ajax({ type: "GET", url: "htt ...

The setInterval function does not function properly in IE8 when set to 0

I have a function called changeColor that updates the styling of certain elements in my HTML. In order to apply this function, I am using a timer like so: var timer = setInterval(changeColor,0); The issue I am encountering is that setting the time interv ...

Implementing Google Calendar access token in JavaScript: A practical guide

I have a question about Google Calendar and I'm hoping you can assist me. I currently have an access_token from Google Calendar that has been stored in the localStorage. const googleAccessToken = e.vc.access_token; localStorage.s ...

Adding styles dynamically using methods is not supported in Vue.js

When it comes to adding styles to an HTML element from methods, I ran into a small hiccup. Here's what I tried: <div class="add-profile-img" v-bind:style="getBackgroundImg()"> The method in question is: getBackgroundImg: function() { return { ...

Caution: It is important for each child within a list to have a distinct "key" prop when using react-input

I'm currently facing an issue with the following code snippet: {array.map((item) => ( <> <input key={item.id} type="checkbox" /> ...

Creating an if statement that validates whether all variables have non-null values

I am still getting the hang of javascript and working on some coding projects from my textbooks. The current task involves creating an if statement to check if the values of the elements referenced by the names fname, lname, and zip are all not null. Here ...

The Field Projection operation is not taking into account the batchSize field name

I have a collection called user_batch which contains the following two documents: [{ _id: ObjectId("594baf96256597ec035df23c"), name: "Batch 1", batchSize: 30, users:[] }, { _id: ObjectId("594baf96256597ec035df234"), name: "Batch 2", batch ...

Iterate through and remove elements within an array containing objects

Within my Vue.js application, I am working with an array of objects that I need to iterate through and display in the web browser. The array consists of four objects, but I only wish to show three based on a user's preference setting stored in a varia ...

Tips for setting up a proxy with an enum

I am facing an issue with setting up a Proxy for an enum. Specifically, I have an enum where I want to assign a value to this.status using a Proxy. However, despite my expectations, the output "I have been set" does not appear in the console. Can anyone ex ...

Guide to generating a continuous flow of numbers in real time with Node.js using sockets, followed by capturing and displaying the data on an HTML page

What is the best method to generate an endless stream of numbers using nodejs and web sockets (preferably socket.io) on a backend server, then display them on an HTML page using JavaScript? ...

What could be causing my directive to not display my scope?

I am currently developing a directive that includes a custom controller, and I am testing the scope functionality. However, I am facing an issue where the ng-show directive is not functioning as expected when trying to test if the directive has a scope fro ...