Reinhard Wedemeyer Reinhard Wedemeyer - 1 year ago 64
Javascript Question

Get variables from button css in Javascript and use them as id

Hi I need a bit of help modifying my script. What I want to do:
I have a small and easy script. It changes the class of an container so I have influence on the behaviour and looking of the container. In my scenario the buttons open a div with a music player.

My problem is that I need to declare all buttons as a script. The button ID is in my case the onclick function (see code).

So when I have 10 or twenty links I need also everytime to modify the script. My idea is to have a script wich gets feed their variables by id's and classes of containers. So I need not to modify the script file.

// JavaScript Document
function AudioFF() {
var FFplayer = document.getElementById(x);
if (FFplayer.classList.contains("audio-hidden")) {
} else {
FFplayer.classList.add("audio-hidden");'audio')).forEach(function(audio) {audio.pause();});

dbbtn.onclick = function() {
x = "deepblue";

swbtn.onclick = function() {
x = "spacewalk";

fbtn.onclick = function() {
x = "forest";

drbtn.onclick = function() {
x = "dreamrhythm";

See here:
Scroll down and choose one of the four sounds.
My idea was to use the same class of a button as an id for the container who needs to fade in with a string. The button has e.g. the class btn_a, btn_b … etc. The containers has the id btn_a, btn_b … I wanted the script to catch the class of the button and use this classname as a variable for getElementById. The closebutton is also using the same script to close the container. Thanks for help :-)

Answer Source

I will recommend to use data attribute instead

example like this:

//register listener like this
var btns = document.querySelectorAll('[data-music]');
btns.forEach(function(elm) {
  elm.addEventListener('click', function(e) {
    //your function
<!--your links-->
<div id="m1"></div>
<div id="m2"></div>
<div id="m3"></div>

<!--just add data-music attribute make it the same with your div id and all set-->
<button data-music="m1">play m1</button>
<button data-music="m2">play m2</button>
<button data-music="m3">play m3</button>

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download