Change DIV CSS based on content (character) length in JavaScript

slb2013
 
on Feb 13, 2022 10:01 PM
959 Views

I would like a Jquery or JavaScript Function that will do when the div display data is less than 30 characters the font-size will be 12px with font-family: Arial and when the div display data is more than 100 characters the font-size is 15px with font-family: Segoe UI else will the default font-size will be 8px.

Your attention is much appreciated.

Please see below:

<style >
.shortstring {
    font-size: 18px;
    font-family: Arial;
    color: #ff6a00;
    /*orange*/
}

.longstring {
    font-size: 12px;
    font-family: Calibri;
    color: #4800ff;
    /*purple*/
}
</style>

 

<script type="text/javascript">
    window.onload = function () {
        LessMore();
    }
    function LessMore() {
        var text = document.getElementById("dvDetails").innerHTML;
        if (currentText.length < 25) {
            document.getElementById("dvDetails").className = "shortstring";
        }
        //else
        if (currentText.length >= 250) {
            document.getElementById("dvDetails").className = "longstring";
        }
    }
</script>

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
arjunv
 
on Feb 15, 2022 10:45 PM

Hi slb2013,

Please refer below sample code.

HTML
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
</head>
<body>
    <style type="text/css">
        .longstring {
            font-size: 15px;
            font-family: 'Segoe UI';
        }

        .shortstring {
            font-size: 12pt;
            font-family: Arial;
        }
    </style>
    <div id="dvDetails">Temperature: 68.4° F , Pressure: Pressure Sensor Error (Transducer Error or Cable Break).  , Current A: 0 Amps , Current B: 0 Amps , Current C: 0 Amps , Mode: Inactive, Sound Level: Abnormal DB 81.34, Voltage: 0 </div>
    <script type="text/javascript">
        window.onload = function () {
            LessMore();
        }

        function LessMore() {
            var text = document.getElementById("dvDetails").innerHTML;
            if (text.length < 30) {
                document.getElementById("dvDetails").className = 'longstring';
            }
            if (text.length >= 30 && text.length <= 250) {
                document.getElementById("dvDetails").className = 'longstring';
            }
            if (text.length > 250) {
                document.getElementById("dvDetails").className = 'shortstring';
            }
        }
    </script>
</body>
</html>

Demo