Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

124
Visualizações
how to change <img src> 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.)

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

There's a couple of things going on with your example:

  1. To compare values your need to either use double == (loose comparison) or triple === (strict comparison) equal signs.
  2. It might be that you are calling var audioState = document.getElementById('musicIcon'); too early, because the document has not been fully parsed yet, and so audioState will be null, instead of the element.
  3. audioState.src will return the full URI to the source after you have assigned a value to it. So comparing it to the relative URI will not match.

Here's a working example, putting it all together (I left out the audio file part):

var audioState;
// create absolute URIs from relative URIs of the images, resolved against document.documentURI
var imageOffUri = new URL('images/musicOff.svg', document.documentURI);
var imageOnUri = new URL('images/musicOn.svg', document.documentURI);
function music() {
    if (audioState.src == imageOffUri) {
        audioState.src = imageOnUri;
        console.log('turned on');
    } else if(audioState.src == imageOnUri) {
        audioState.src = imageOffUri;
        console.log('turned off');
    }
}

// wait for the document to be fully parsed
document.addEventListener('DOMContentLoaded', function() {
  audioState = document.getElementById('musicIcon');
});
.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;
}
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title></title>
</head>
<body>
  <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>
</body>
</html>

about 4 years ago · Juan Pablo Isaza Relatório

0

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

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda