How do I pass this image as a parameter?

Asked

Viewed 493 times

1

The question is as follows, as I pass the image as 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)';
} 

1 answer

5

Pass as parameter was not the problem, but use 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.


Otherwise the function would be like this:

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

And you call her that:

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

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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.