Skip to content
Advertisement

how to change with javascript

I have a Javascript function that I been dealing with for a few hours,

Javascript:

var musicFile = new Audio('audio/Ice.mp3');
var audioState = document.getElementById('musicIcon');

function music() {
    if (audioState.src = 'images/musicOff.svg') {
        musicFile.play();
        audioState.src = 'images/musicOn.svg';
    } else if(audioState.src = 'images/musicOn.svg') {
        musicFile.pause();
        musicFile.currentTime = 0;
        audioState.src = 'images/musicOff.svg';
    }
}

HTML:

<ul class="tabs" style="top: 0px; right: 0px; width: 210px; right: 10px; text-shadow: 1px 1px indigo;">
    <li class="tab" onclick="music()">
        <img id="musicIcon" src="images/musicOff.svg" width="32" height="32">
    </li>
</ul>

CSS:

.tabs {
    position: absolute;
    display: flex;
    list-style-type: none;
    margin: auto;
    padding: 0px;
    width: 800px;
    height: 30px;
}
.tab {
    position: relative;
    top: 30%;
    width: 15%;
    height: 20px;
    background:royalblue;
    border: 0px transparent;
    border-radius: 10px;
    padding: 10px;
    margin: 0px;
    margin-right: 15px;
    text-align: center;
    font-size: 16px;
    font-family: monospace;
    color: white;
    cursor: pointer;

}
.tab:hover {
    text-align:center;
    background-color: #CCC;
}

The <li> tag is meant to act as a button, and it does everything in the function, (changes .svg Icon and plays the music) but the second time I click it again, nothing happens. I also checked the console, and no errors.

I would really appreciate some help, and maybe some tips in general. (New to Javascript, not looking to use jQuery right now.)

Advertisement

Answer

you’re forgetting to use double equals to do a comparation. Change = to ==

audioState.src is returning absolute path, try change it for the method getAttribute('src') on all comparations. like that:

audioState.getAttribute('src') == 'images/musicOff.svg'

and to change src value, try to use setAttribute('attribute', 'newValue') method like that:

audioState.setAttribute('src', 'images/musicOff.svg');

hope it help u

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement