By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,945 Members | 1,432 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,945 IT Pros & Developers. It's quick & easy.

Can't simulate a "button" in JavaScript

P: 24
I'm trying to simulate buttons using images. I tried many ways and I don't seem to get it to work as far as the button label is concerned. I tried manipulating "top" and "left" and now the margins and I'm getting bizarre results. This is not the actual code. I did what I had to do to make it independent from the website I'm working on and to "reduce" the problem to the bare minimum factors.

Expand|Select|Wrap|Line Numbers
  1. <style type="text/css">
  2. div.btn {
  3.   width: 80px;
  4.   height: 22px;
  5. }
  6.  
  7. img.btn {
  8.   position: absolute;
  9.   left: 10px;
  10.   top: 10px;
  11. }
  12.  
  13. #btnLabel1 {
  14.   color: white;
  15.   margin-left: 1px;
  16.   margin-top: 1px;  
  17. }
  18. </style>
  19.  
  20. <script type="text/javascript">
  21. function BtnMouseUp(objNum) {
  22.    var lbl = document.getElementById("btnLabel" + objNum);
  23.    alert(parseInt(lbl.style.marginLeft);
  24.    lbl.style.marginLeft = (parseInt(lbl.style.marginLeft) - 5) + "px"; 
  25.    lbl.style.marginTop = (parseInt(lbl.style.marginTop) - 5) + "px";
  26.    document.getElementById("btnImage" + objNum).src = "btn_reg.bmp";
  27. }
  28.  
  29. function BtnMouseDown(objNum) {
  30.    var lbl = document.getElementById("btnLabel" + objNum);
  31.    lbl.style.marginLeft = (parseInt(lbl.style.marginLeft) + 5) + "px"; 
  32.    lbl.style.marginTop = (parseInt(lbl.style.marginTop) + 5) + "px";
  33.    document.getElementById("btnImage" + objNum).src = "btn_prsd.bmp";
  34. }
  35. </script>
  36.  
  37. <body>
  38. <div class="btn" onload="BtnMouseUp('1');" onmousedown="BtnMouseDown('1');" onmouseup="BtnMouseUp('1');">
  39. <img class="btn" id="btnImage1" src="btn_reg.bmp"  />
  40. <span id="btnLabel1">Hello</span>
  41. </div>
  42. </body>
  43.  
Aug 5 '09 #1
Share this Question
Share on Google+
1 Reply


P: 5
You can try padding-left of the div instead of the margin of its content. But is it really worth it? All that javascript...
If you just need a button with an image use <button><img/>hello</button>
And jQuery can ease your pain. :)
Aug 5 '09 #2

Post your reply

Sign in to post your reply or Sign up for a free account.