How To Use CSS Style TextAlign Properties In JavaScript

admin_img Posted By Bajarangi soft , Posted On 29-09-2020

In Java Script we can do text align on click of button so today in this article we are going to discuss how to align text using java script

How To Use CSS Style TextAlign Properties In JavaScript

The textAlign property sets or returns the horizontal alignment of text in a block level element.

Syntax and Usage

Return the textAlign property:
object.style.textAlign

Set the textAlign property:
object.style.textAlign = "left|right|center|justify|initial|inherit"
 

Property Values
 

Value Description
left Aligns the text to the left. This is default
right Aligns the text to the right
center Centers the text
justify The text is justified
initial Sets this property to its default value. 
inherit Inherits this property from its parent element. 


Example(1)
<button class="btn btn-success" onclick="ta_center()">Align to center</button>

<h2 id="demo1">This is an example paragraph.</h2>
<script>
    function ta_center() {
        document.getElementById("demo1").style.textAlign = "center";
    }
</script>

In above example when you click button the div text will be align to center.

Example(2)
<h2 id="demo2" style="text-align:right;">This is an example paragraph.</h2>

<button class="btn btn-success" type="button" onclick="get_alert()">Return text alignment of p</button>
<script>
    function get_alert() {
        alert(document.getElementById("demo2").style.textAlign);
    }
</script>

In above example when you click button the get alert message as your text at right side.



Complete code for Use CSS Style TextAlign Properties In JavaScript
<!DOCTYPE html>
<html>
<head>
    <title>Use CSS Style TextAlign Properties In JavaScript</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
</head>
<style>
    h1{
        color: red;

    }
</style>

<body>
<div class="container">
       <div class="text-center">
        <h1>Use CSS Style TextAlign Properties In JavaScript</h1>
    </div>
    <br>
       <div class="well">

           <button class="btn btn-success" onclick="ta_center()">Align to center</button>

           <h2 id="demo1">This is an example paragraph.</h2>


           <h2 id="demo2" style="text-align:right;">This is an example paragraph.</h2>

           <button class="btn btn-success" type="button" onclick="get_alert()">Return text alignment of p</button>
       </div>
</body>
</html>
<script>
    function ta_center() {
        document.getElementById("demo1").style.textAlign = "center";
    }
    function get_alert() {
        alert(document.getElementById("demo2").style.textAlign);
    }
</script>

 

Related Post