Search code examples
javascriptcssbuttonsize

How do I change a button size in javascript


I'm using javascript to create buttons in a chrome extension but I can't find a way to change the size of the button, here's the code.

var buttonShort = document.createElement("button");
buttonShort.innerHTML = "Generate Short Password";

var body = document.getElementsByTagName("body")[0];
body.appendChild(buttonShort);

buttonShort.addEventListener ("click", function() {
  var newWindow = window.open();
  newWindow.document.write("The generated Password is: '" + short() + "'");
  newWindow.focus()
});

I need to change the size of the button (mainly the width) so if you have any suggestions, please say. Also if you're going to say use CSS, I don't know how to add a CSS file to a javascript file so please tell me how to do that if you don't mind.

Thanks.


Solution

  • Use the style.width property before you append the button element to the body, like so :

    var buttonShort = document.createElement("button");
    buttonShort.innerHTML = "Generate Short Password";
    
    var body = document.getElementsByTagName("body")[0];
    
    buttonShort.style.width = '200px'; // setting the width to 200px
    buttonShort.style.height = '200px'; // setting the height to 200px
    buttonShort.style.background = 'teal'; // setting the background color to teal
    buttonShort.style.color = 'white'; // setting the color to white
    buttonShort.style.fontSize = '20px'; // setting the font size to 20px
    
    body.appendChild(buttonShort);
    
    buttonShort.addEventListener("click", function() {
      var newWindow = window.open();
      newWindow.document.write("The generated Password is: '" + short() + "'");
      newWindow.focus();
    });

    all the other CSS properties are accessible through the style object (width, height, color, ...etc)

    NOTE: beware of properties like font-size you cannot use the - as an object key so the way you would go about doing that is by camelCasing it like so fontSize.