2
var text = document.querySelector('p')
for(var i=10px; i<=40px; i++)
  text.style.fontSize = i; 

I want a script which increases the font size in every iteration of the for-loop. The above code is the prototype of my requirement (which won't work since pixels can't be assigned to a variable). Help me providing the correct code.

3
  • There is no 10px literal. Commented Mar 31, 2018 at 7:25
  • Is the number of you p tags dynamically or fixed? Commented Mar 31, 2018 at 7:29
  • Just wonder if you have 1 p tag and want to increase only that one like an animation or if you want to have every p tag with higher font size. Commented Mar 31, 2018 at 7:33

4 Answers 4

3

You probably want to use setTimeout recursion instead, so the text doesn't increase in size instantly:

var text = document.querySelector('p');

function increaseTextSize(size) {
  text.style.fontSize = size + 'px'; 
  if (size <= 40) setTimeout(increaseTextSize, 50, size + 1);
}
increaseTextSize(10);
<p>my text</p>

Sign up to request clarification or add additional context in comments.

Comments

3

You can also try out this demo using CSS transition effect:

// After 500ms change the font from 10 to 60px
// and css will take care of the rest
setTimeout(() => {
  var text = document.querySelector('p');
  text.style.fontSize = '60px';
  text.style.color = 'blue';  // <-- you can also add color effects, if you want
}, 500);
p {
  font-size: 10px;
  color: red;
  -webkit-transition: all 2.5s ease;
  -moz-transition: all 2.5s ease;
  -o-transition: all 2.5s ease;
  -ms-transition: all 2.5s ease;
}
<p>Hello World!</p>

Comments

2
var text = document.querySelector('p')

for (var i = 10; i <= 40; i++) {
  text.style.fontSize = `${i}px`;
}

You cannot append px in the loop since it has to be an integer.

Comments

0

var text = document.querySelector('p');

function increaseTextSize(size) {
  text.style.fontSize = size + 'px'; 
  if (size <= 40) setTimeout(increaseTextSize, 50, size + 1);
}
increaseTextSize(10);
<p>my text</p>

Dfhg

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.