Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Help - Javascript targeting SVG problem

Hey guys, standard "I'm in a pickle" post. I need a javascript guru to help me out.

I creating a form for someone that makes custom watches, the form is fine for choosing the colours but I thought it would be awesome to have the sections that can be customised in .svg change colour also.

I have a really rough mock up here so you get the idea. But the svg's aren't changing.

I've included the gist of the code here if anyone knows how to target the svg properly and I'm using JSColor

This has been doing my head in so any help would be awesome.

This is an example of the code I have trying to get it to target part of the SVG image but it's not working :( -

<p><input class="color"
    onchange="document.getElementsByTagName('SEC1')[0].style.fill = '#'+this.color"> - Bezel Colour
</p>

Thank you

2 Answers

When selecting internal SVG elements just reference them by their id name.

<input class="color" onChange="sec1.style.fill='#'+this.color">

Working Demo: http://codepen.io/jamesbarnett/pen/GFtyc/

ref: http://stackoverflow.com/a/9873285/1756132)

I'll avoid any awkwardness this time, but thanks :)

I was experimenting with this myself a while back, I've got a pen here http://codepen.io/KryptoniteDove/pen/iFHAa that show's how you can alter the colors using jQuery and the attr method.

Basically you want to target the fill and stroke attributes of the SVG element and change the colors on those. Here's a QnD example using your image.

Working examples jQuery: http://jsbin.com/lareb/1/ Vanilla Javascript: http://jsbin.com/lareb/2/

//jQuery
$( '#DW6900' ).attr({
  fill : '#000',
  stroke : 'red',
  'stroke-width' : '10'
});


// Vanilla JS Example
var d = document;

// Helper function
function setAttributes( el, attrs ) {
  for ( var key in attrs ) {
    el.setAttribute( key, attrs[key] );
  }
}

setAttributes(d.getElementById( 'DW6900' ), {
     fill : '#000',
     stroke : 'red',
     'stroke-width' : '10'
});

Thanks Richard, I'm going to play around with some of those examples and hopefully nail this :)

Best of luck!