Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to give html button tag an image

Tags:

html

button

I am wondering if there is a way to give the HTML button tag, <button> an image so the image is click-able on my webpage. That way when users click on the image I can have other things happen

This doesn't seem to be working, and was wondering if it is even possible

HTML code -

<button>
<img src="images/dagger.png" width="10%" height="10%" id="dagger" />
</button>
like image 265
Matt Murphy Avatar asked Jan 11 '12 11:01

Matt Murphy


Video Answer


3 Answers

Not quite sure what you are trying to achieve but maybe this example helps.

HTML

<button>
<img src="http://www.w3.org/html/logo/downloads/HTML5_Logo_32.png" id="dagger" />
</button>

JavaScript

$(function(){
    $("#dagger").click(function(){
        alert("click");
    }); 
});
like image 193
Maurice Avatar answered Oct 24 '22 18:10

Maurice


You could set the image as button background

button {
    background-image:url('images/dagger.png');
}
like image 42
Simone Avatar answered Oct 24 '22 19:10

Simone


I was having similar issues, and thought I would drop this post for anyone in the future that sees this thread.

From my understanding, you're not wanting a BUTTON, but a clickable image that acts as a button. Here is what I did:

HTML:

<img src="images/dagger.png" width="10%" height="10%" id="dagger" />

JavaScript/jQuery:

<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
 $("#dagger").click(function(){
     // what you wanted your button to do when user clicks it    
 });
</script>

By doing it this way, you get rid of the normal "button" image, and you can use whatever image you want as your clickable button. As well, you get the same functionality that you're wanting from the button, and it opens up many other paths to achieving your purposes.

Hope it helps!


Another method I use is simply putting the onclick event on the img itself to call a function.

html:

<img src="images/dagger.png" width="10%" height="10%" id="dagger" onclick="myFunction()" />

JS:

<script>
 myFunction() {
   // what I want to happen if user clicks image
 }
</script>

Depending upon what you're doing, and what you're trying to manipulate, all of the examples on this page will provide you with better/worse ways of doing it. Using the onclick event within the img tag, you can pass variables/information to the function to utilize, and then have the function relay it to your PHP/ASP/etc.. As well, if you were dealing with a form, you can have your function handle information/submission, rather than the default submission that forms use. Use your imagination with the problems you come across, and decide which method works out better. Never settle for learning just one way of doing something.

like image 2
Fata1Err0r Avatar answered Oct 24 '22 18:10

Fata1Err0r