To use jQuery to animate the font size of a paragraph, we can use the jQuery animate() method to change the font-size property of that element.
$("#p1").animate({fontSize: "30px"});
Let’s say we have the following HTML:
<div id="div1">
<p>We will change the font size of this text.</p>
</div>
If we want to animate the font size of the paragraph from its default size of 18px to 30px, we will use the jQuery animate() method in the following JavaScript code.
$("#div1 p").animate({fontSize: "30px"});
If you are using WordPress, don’t forget to change the $ to jQuery as below:
jQuery("#div1 p").animate({fontSize: "30px"});
Using jQuery to Animate the Font Size of Text with a Click
To animate the font size of text using jQuery, we can combine the animate() method with a click event.
Let’s say we have the following HTML and we want to animate the font size of the first paragraph to 30px. We will provide the user a button to animate the text to 30px and a button to animate it back to 18px
<div>
<p id="p1">This is some text</p>
<p id="p2">This is some text</p>
<div id="click-me1" class="click-me">Animate font size to 30px</div>
<div id="click-me2" class="click-me">Animate font size back</div>
</div>
We can utilize both the jQuery click() and animate() methods to animate the font size of the first line of text and make it larger and smaller.
Here is the JavaScript code:
$("#click-me1").click(function(){
$("#p1").animate({fontSize: "30px"});
});
$("#click-me2").click(function(){
$("#p1").animate({fontSize: "18px"});
});
The final code and output for this example of how to animate the font size of text using jQuery is below:
Code Output:
This is some text
This is some text
Full Code:
<div>
<p id="p1">This is some text</p>
<p id="p2">This is some text</p>
<div id="click-me1" class="click-me">Animate font size to 30px</div>
<div id="click-me2" class="click-me">Animate font size back</div>
</div>
<script>
$("#click-me1").click(function(){
$("#p1").animate({fontSize: "30px"});
});
$("#click-me2").click(function(){
$("#p1").animate({fontSize: "18px"});
});
</script>
Hopefully this article has been useful for you to understand how to use jQuery to animate the font size of a paragraph.
Leave a Reply