0

I have an 10 HTML buttons that I need to change the value of a javascript variable when clicked.

song2 = "mp3Player/kingRight.mp3";
 function returnVar2(song2) { return this[song2]; }

Song2 needs a new URL depending on which button is clicked.

Having a hard time figuring this out.

0

2 Answers 2

2
<button id="b1">Button 1</button>
<button id="b2">Button 2</button>
<script>
var b1 = document.getElementById('b1'), b2 = document.getElementById('b2');
var x = "Hello!";
function showX() {
    alert(x);
}
b1.onclick = function() {
    x = "button one";
    showX();
};
b2.onclick = function() {
    x = "button two";
    showX();
};
</script>

Demo

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks, that explained a lot. I still have one question though - I need the run "function returnVar2(song2)" and have it return "var song2 = x" when the button is clicked. I have some AS3 code listening for this function and variable return, and I need it to see this on button click. Thanks a lot for the help!
Yeah definitely. I've just been stuck on this for hours. My javascript skills are not great...
Can you add some of the pertinent stuff the demo fiddle I made so I can see how better to assist?
Ok, your demo has been updated. I would like to be able to run the function returnVar2(song2) on a button click and have it return the variable song2 with the URL. Thanks again!
2

HTML:

<div id="mp3buttons">
    <div title="mp3Player/kingRight.mp3">King Right</div>
    <div title="mp3Player/AnotherSong.mp3">Another Song</div>
    etc.
</div>

JavaScript:

var mp3buttons = document.getElementById( 'mp3buttons' );

mp3buttons.onclick = function ( e ) {        
    var url = e.target.title;
    // do stuff with this URL
};

So, you put your buttons inside a wrapper. For each button, you place the URL inside the title attribute (or some other appropriate attribute).

In JavaScript code, you bind a click handler to the wrapper. The clicked button is referenced with e.target.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.