Home > Back-end >  How to center and enlarge text using javascript?
How to center and enlarge text using javascript?

Time:11-24

I want to replace div content with a random text quotation (I am coding a Chrome web extension) which the code below does; but I don't know how to use javascript to manipulate the text so that I can center it, enlarge the text, bump the text down a few lines, etc. As I do not have access to the original HTML (this is for a Chrome Extension), I need to accomplish this with javascript. Is this possible?

const quotes = [
'Quotation 0.',
'Quotation 1.',
'Quotation 2.'
];
index = Math.floor(Math.random() * quotes.length);
document.getElementById('pageContent').outerHTML = quotes[index];

CodePudding user response:

js does not cause the rendering of text, the browser interprets the html and css to render the text. You can use js to inject html and css for you desired effect. If you can not directly edit the html or css document, you can use inline stylings to create visual effects, however chrome extension do have the ability to inject css as well as js.

How about something like modification to the code you provided:

const quotes = [
  'Quotation 0.',
  'Quotation 1.',
  'Quotation 2.'
];
const index = Math.floor(Math.random() * quotes.length);
const h2 = document.createElement("h2");
h2.style.cssText = `
  text-align: center;
  font-size: 3rem;
  margin: 1rem;
`;
h2.innerText = quotes[index];

document.getElementById('pageContent').appendChild(h2);

CodePudding user response:

This is really a Cascading Style Sheets (CSS) question.

You can use CSS's

text-align: "center"
font-size: "130%"

I also advise you to look into what other settings font-size can have (vis-a-vis percentage). It is better if you can apply these styles on a CSS stylesheet. But if you want to do it in JavaScript, you can do

myElement.style.textAlign = "center";
myElement.style.fontSize = "130%"
  • Related