How to set the shadow effect of a text with JavaScript?

The textShadow property in JavaScript allows you to add shadow effects to text elements. This property accepts values for horizontal offset, vertical offset, blur radius, and color.

Syntax

element.style.textShadow = "h-shadow v-shadow blur-radius color";

Parameters

  • h-shadow: Horizontal offset of the shadow (required)
  • v-shadow: Vertical offset of the shadow (required)
  • blur-radius: Blur distance of the shadow (optional)
  • color: Color of the shadow (optional)

Example: Basic Text Shadow

<!DOCTYPE html>
<html>
<body>
   <button onclick="addShadow()">Add Text Shadow</button>
   <button onclick="removeShadow()">Remove Shadow</button>

   <div id="myText" style="font-size: 24px; padding: 20px;">
      This is sample text for shadow effect demonstration.
   </div>

   <script>
      function addShadow() {
         document.getElementById("myText").style.textShadow = "2px 2px 4px #888888";
      }
      
      function removeShadow() {
         document.getElementById("myText").style.textShadow = "none";
      }
   </script>
</body>
</html>

Example: Multiple Text Shadows

You can apply multiple shadows by separating them with commas:

<!DOCTYPE html>
<html>
<body>
   <button onclick="multiShadow()">Multiple Shadows</button>

   <div id="multiText" style="font-size: 28px; padding: 20px; text-align: center;">
      MULTIPLE SHADOW EFFECT
   </div>

   <script>
      function multiShadow() {
         document.getElementById("multiText").style.textShadow = 
            "2px 2px 2px #ff0000, 5px 5px 5px #0000ff, 8px 8px 8px #00ff00";
      }
   </script>
</body>
</html>

Common Use Cases

Effect Code Example Description
Drop Shadow "2px 2px 4px #666" Standard shadow effect
Glow Effect "0 0 10px #ffff00" Text appears to glow
Embossed Text "1px 1px 0 #fff" Raised text appearance

Conclusion

The textShadow property provides an effective way to enhance text appearance with shadow effects. You can create simple drop shadows or complex multiple shadow combinations to achieve various visual effects.

Updated on: 2026-03-15T23:18:59+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements