W3Schools.com (2024)

SVG + JavaScript

SVG can be used together with JavaScript to modify and animate SVG elements.

SVG Simple Script

In this example, we create a red circle with a radius of 25. Click the button to change the radius to 50:

Here is the SVG code:

Example

<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
<circle id="circle1" cx="50" cy="50" r="25" style="fill:red;" />
</svg>

<input type="button" value="Change Radius" onclick="changeRadius()" />

<script>
function changeRadius() {
document.getElementById("circle1").setAttribute("r", "50");
}
</script>

Try it Yourself »

Code explanation:

  • Add an id attribute to the <circle> element
  • Create a script within <script> tags
  • Get a reference to the SVG element with the getElementById() function
  • Change the r attribute using the setAttribute() function
  • Add an <input type="button"> element to run the JavaScript when clicked

SVG Change CSS

In this example, we create a red circle. Click the button to change the fill color to green:

Here is the SVG code:

Example

<svg width="200" height="100" xmlns="http://www.w3.org/2000/svg">
<circle id="circle2" cx="50" cy="50" r="25" style="fill:red;" />
Sorry, your browser does not support inline SVG.
</svg>

<input type="button" value="Change Style" onclick="changeStyle()" />

<script>
function changeStyle() {
document.getElementById("circle2").style.fill="green";
}
</script>

Try it Yourself »

Code explanation:

  • Add an id attribute to the <circle> element
  • Create a script within <script> tags
  • Get a reference to the SVG element with the getElementById() function
  • Set a new fill color with style.fill
  • Add an <input type="button"> element to run the JavaScript when clicked

SVG Change Attribute Values and CSS

In this example, we create a red circle. Click the button to change the radius, the x position, fill color, and add a stroke color:

Here is the SVG code:

Example

<svg width="200" height="120" xmlns="http://www.w3.org/2000/svg">
<circle id="circle3" cx="50" cy="60" r="25" style="fill:red;" />
</svg>

<input type="button" value="Change Circle" onclick="changeMe()" />

<script>
function changeMe() {
var c = document.getElementById("circle3");
c.setAttribute("r", "50");
c.setAttribute("cx", "150");
c.style.fill="green";
c.style.stroke="red";
}
</script>

Try it Yourself »

SVG Script for Animation

In this example, we create a red circle. Click the two buttons to start and stop the animation:


Here is the SVG code:

Example

<svg width="600" height="100" xmlns="http://www.w3.org/2000/svg">
<circle id="circle4" cx="50" cy="50" r="50" style="fill:red;" />
</svg>

<script>
var t = null;

function start() {
if(t == null) {
t = setInterval(animate, 20);
}
}

function stop() {
if(t != null) {
clearInterval(t);
t = null;
}
}

function animate() {
var circle = document.getElementById("circle4");
var cx = circle.getAttribute("cx");
var newCX = 2 + parseInt(cx);
if(newCX > 600) {
newCX = 50;
}
circle.setAttribute("cx", newCX);
}
</script>

<br/>
<input type="button" value="Start" onclick="start()" />
<input type="button" value="Stop" onclick="stop()" />

Try it Yourself »

Code explanation:

  • The start() and stop() functions start and stop the animation
  • The animation starts by setting up a timer (t) which calls the animate() function every 20 milliseconds with the setInterval() function
  • The animation is stopped by clearing the t timer
  • The animation is performed inside the animate() function
  • Get a reference to the <circle> element with the getElementById() function
  • Get the value of the cx attribute with the getAttribute() function
  • Convert the value of the cx attribute to a number with parseInt(). Then add 2 to the cx value
  • Test if the newCX value is larger than 600 (which is the width of the SVG "window"), then reset it to 50 (which is the original start position)
  • Put the newCX value into the cx attribute of the <circle> element with the setAttribute() function. This moves the circle to the new cx-position

W3schools Pathfinder

Track your progress - it's free!

W3Schools.com (2024)
Top Articles
Easy Way To Convert PFX to .Crt & .Key Files In 10 Minutes
Buying property in Japan as a Brit
Urist Mcenforcer
Kansas City Kansas Public Schools Educational Audiology Externship in Kansas City, KS for KCK public Schools
Regal Amc Near Me
Dollywood's Smoky Mountain Christmas - Pigeon Forge, TN
Falgout Funeral Home Obituaries Houma
Hertz Car Rental Partnership | Uber
Acts 16 Nkjv
Tap Tap Run Coupon Codes
Rubfinder
Chastity Brainwash
Craigslist Jobs Phoenix
Keurig Refillable Pods Walmart
Washington, D.C. - Capital, Founding, Monumental
OSRS Dryness Calculator - GEGCalculators
Cooking Fever Wiki
Illinois Gun Shows 2022
Patrick Bateman Notebook
Wal-Mart 140 Supercenter Products
Puretalkusa.com/Amac
The Exorcist: Believer (2023) Showtimes
91 East Freeway Accident Today 2022
China’s UberEats - Meituan Dianping, Abandons Bike Sharing And Ride Hailing - Digital Crew
ELT Concourse Delta: preparing for Module Two
Pjs Obits
Busted Mcpherson Newspaper
Aes Salt Lake City Showdown
27 Modern Dining Room Ideas You'll Want to Try ASAP
Villano Antillano Desnuda
Speechwire Login
Trust/Family Bank Contingency Plan
The Ultimate Guide to Obtaining Bark in Conan Exiles: Tips and Tricks for the Best Results
Metro By T Mobile Sign In
Ultra Clear Epoxy Instructions
Yoshidakins
The Pretty Kitty Tanglewood
Omnistorm Necro Diablo 4
Manatee County Recorder Of Deeds
Ksu Sturgis Library
Shane Gillis’s Fall and Rise
VPN Free - Betternet Unlimited VPN Proxy - Chrome Web Store
Alpha Labs Male Enhancement – Complete Reviews And Guide
VDJdb in 2019: database extension, new analysis infrastructure and a T-cell receptor motif compendium
Az Unblocked Games: Complete with ease | airSlate SignNow
UWPD investigating sharing of 'sensitive' photos, video of Wisconsin volleyball team
Spreading Unverified Info Crossword Clue
Tyco Forums
Diario Las Americas Rentas Hialeah
Campaign Blacksmith Bench
786 Area Code -Get a Local Phone Number For Miami, Florida
Latest Posts
Article information

Author: Kerri Lueilwitz

Last Updated:

Views: 6059

Rating: 4.7 / 5 (67 voted)

Reviews: 82% of readers found this page helpful

Author information

Name: Kerri Lueilwitz

Birthday: 1992-10-31

Address: Suite 878 3699 Chantelle Roads, Colebury, NC 68599

Phone: +6111989609516

Job: Chief Farming Manager

Hobby: Mycology, Stone skipping, Dowsing, Whittling, Taxidermy, Sand art, Roller skating

Introduction: My name is Kerri Lueilwitz, I am a courageous, gentle, quaint, thankful, outstanding, brave, vast person who loves writing and wants to share my knowledge and understanding with you.