Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add image to button via Javascript?

I am trying to add image to buttons I have using Javascript but I can't seem to get it working. I have sucessfully added image using HTML5, however, for my needs I need to add the image via javascript.

Below is what I have written to add images via HTML.

<button class="button" id="Ok"><img src="images/ok.png"></button>

Below is what I have tried to add image via Javascript but it doesn't seem to work.

var buttons = document.getElementsByClassName("button");
for (var b = 0; b < buttons.length; b++) {
      buttons[b].src = "images\ok.png";   
  }

I am not to sure what I am doing wrong, any help would be nice. Thanks.

like image 694
Henry Avatar asked Dec 01 '22 13:12

Henry


2 Answers

I don't know if this is what you need..

<button id="button"></button>

<script type="text/javascript">
    var buttons = document.getElementById("button");
    buttons.innerHTML = '<img src="images\ok.png" />';
</script>
like image 55
MGB C Avatar answered Dec 04 '22 01:12

MGB C


I think this may be what you're looking for.... this will set the buttons direct background as the image. But you must set the width and height options to your images width and height or it will be cut off or have white space, depending on the size of the button and image.

<style>
  button.button#ok
  {
    width:100px;
    height:100px;
  }
</style>
<button class="button" id="ok"></button>
<script>
  var buttons=document.getElementsByClassName("button");
  for(var b=0;b<buttons.length;b++)
  {
    if(buttons[b].id=="ok")
    {
      buttons[b].style.background="url('images/ok.png')";   
    }
  }
</script>

Edit, source

Here is the code in action:

http://js.x10.bz/helpstack/35742199/button.html

Here is the source of the code(which is above though):

http://js.x10.bz/helpstack/35742199/button.txt

And here is the image i used:

http://js.x10.bz/helpstack/35742199/cookies.jpg

like image 43
James Karlton Stone Avatar answered Dec 04 '22 01:12

James Karlton Stone