How do I pass this image as a parameter?

1

The question is as follows, how do I pass the image as a parameter to use it in javascript with tried in the code below?

HTML

<!doctype html>
<html lang="pt-br">
<head>
<meta charset="utf-8"></meta>
<script type="text/javascript" src="javascript.js"></script>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div id="botao_1"class="bgbotaorank" style="background-image:url('twitter.png');"  onclick="muda_imagem('botao_1','twitter.png');">
</div>
<div id="botao_2" class="bgbotaorank" onclick="muda_imagem('botao_2','twitter.png');">
</div>
<div id="botao_3" class="bgbotaorank">
</div>
<div id="botao_4" class="bgbotaorank"></div>
</body>
</html>

JavaScript

function muda_imagem(id, imagem) {
document.getElementById("botao_1").style.backgroundImage = "url('red.png')";
document.getElementById("botao_2").style.backgroundImage = "url('red.png')";
document.getElementById("botao_3").style.backgroundImage = "url('red.png')";
document.getElementById("botao_4").style.backgroundImage = "url('red.png')";
document.getElementById(id).style.backgroundImage = 'url(imagem)';
} 
    
asked by anonymous 09.01.2016 / 07:31

1 answer

5

Passing as a parameter was not the problem, but using the parameter.

See the adjusted function:

function muda_imagem(id, imagem) {
  document.getElementById(id).style.backgroundImage = 'url(' + imagem + ')';
}
/*
 * Daqui pra baixo é só teste:
 */

div { width:180px;height:180px;background-color:#f90 }
<div id="botao_1" onclick="muda_imagem('botao_1','http://i.stack.imgur.com/iOE9F.jpg');">
Clique-me</div>

Click "Run" right above and take the test.


Another way would be to function like this:

 document.getElementById(id).style.backgroundImage = imagem;

And you call it like this:

 muda_imagem( 'botao_1', 'url(http://i.stack.imgur.com/iOE9F.jpg)' );

This second would be useful if you want to call both images with url and data: using the same function (and who knows gradients , etc.).

    
09.01.2016 / 07:52