Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda