Changing colour using Javascript [duplicate] - javascript

I created a SVG file contains 5 polygons, then I need to embed Javascript so 4 of the polygons' color changes to Red when mouseover, and when mouseout, the color changes to Green. I tried to write the code but it didn't work, what could be the problem? Thanks for help and tips!
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<svg width="26cm" height="24cm" viewBox="0 0 2600 2400" version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink= "http://www.w3.org/1999/xlink">
<script type="text/javascript">
<![CDATA[
document.getElementById("test").onmouseover = function(){changeColor()};
function changeColor() {
document.getElementById("test").style.color = "red";
}
document.getElementById("test").onmouseout = function(){changeColor()};
function changeColor() {
document.getElementById("test").style.color = "green";
}
]]>
</script>
<circle cx="1600" cy="700" r="600" fill="yellow" stroke="black" stroke-width="3"/>
<ellipse id="test" cx="1300" cy="500" rx="74" ry="120" fill="blue" stroke="black" stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/>
<ellipse id="test" cx="1850" cy="500" rx="74" ry="120" fill="blue" stroke="black" stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/>
<rect id="test" x="1510" y="650" width="160" height="160" fill="blue" stroke="black" stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/>
<polygon id="test" points="1320,800 1370,1080 1820,1080 1870,800 1820,1000 1370,1000" name="mouth" fill="blue" stroke="black" stroke-width="3" onmouseover="javascript:red();" onmouseout="javascript:green();"/>
</svg>

For what you are doing I would recommend using pure CSS.
Here is some working code.
svg:hover .recolor {
fill: red;
}
As you see, you can just use the :hover event in CSS to recolor the necessary elements. And set them to your default color (green), which will take effect when the user is not hovered.

You have various errors
you've two functions called changeColor, functions must have unique names
SVG does not use color to colour elements, instead it uses fill (and stroke).
id values must be unique, you probably want to replace id by class and then use getElementsByClassName instead of getElementById. If you do that you'll need to cope with more than one element though. I've not completed that part, you should try it yourself so you understand what's going on.
I've removed all but one id from my version so you can see it working on the left eye.
document.getElementById("test").onmouseover = function(){changeColor()};
function changeColor() {
document.getElementById("test").style.fill = "red";
}
document.getElementById("test").onmouseout = function(){changeColor2()};
function changeColor2() {
document.getElementById("test").style.fill = "green";
}
<svg width="26cm" height="24cm" viewBox="0 0 2600 2400" version="1.1"
xmlns="http://www.w3.org/2000/svg"
xmlns:xlink= "http://www.w3.org/1999/xlink">
<circle cx="1600" cy="700" r="600" fill="yellow" stroke="black" stroke-width="3"/>
<ellipse id="test" cx="1300" cy="500" rx="74" ry="120" fill="blue" stroke="black" stroke-width="3"/>
<ellipse cx="1850" cy="500" rx="74" ry="120" fill="blue" stroke="black" stroke-width="3" />
<rect x="1510" y="650" width="160" height="160" fill="blue" stroke="black" stroke-width="3" />
<polygon points="1320,800 1370,1080 1820,1080 1870,800 1820,1000 1370,1000" name="mouth" fill="blue" stroke="black" stroke-width="3"/>
</svg>

Related

How to trigger click of both elements, when clicking overlapping area

I have two elements overlapping each other, Both has click events. Clicking on each element works fine.
If I click on an overlapping area as shown below, can I trigger the click of both?
Below is my code
$("#circle1").click(function(d) {
alert("circle1");
});
$("#circle2").click(function(d) {
alert("circle2");
});
.path {
fill: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<svg width="525" height="226">
<circle id="circle1" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
<circle id="circle2" cx="80" cy="50" r="40" stroke="black" stroke-width="3" fill="transparent" />
</svg>
I would use clip-path to get the intersection of the 2 circles. Then I would attach the event to intersection.
intersection.addEventListener("click",()=>{
console.log("intersection")
})
circle{stroke-width:3;stroke:black;}
svg{border:1px solid}
<svg id="svg" viewBox="0 0 525 226">
<defs>
<circle id="circle1" cx="50" cy="50" r="40" />
<circle id="circle2" cx="80" cy="50" r="40" />
<clipPath id="clip"><use xlink:href="#circle2" />
</clipPath>
</defs>
<use xlink:href="#circle1" class="circle" fill="red" />
<use xlink:href="#circle2" class="circle" fill="transparent" />
<use xlink:href="#circle1" id="intersection" clip-path="url(#clip)" fill="gold" />
</svg>
You should not rely on any approach that calculates the position of the intersection or that creates another element just to compute the intersection. Such approaches will eventually fail or simply become too complicated and cumbersome.
Instead of that, use the event itself and a method like document.elementFromPoint to get all elements under the click. For instance, you can use document.elementFromPoint “recursively”, as described here. Then, using selection.dispatch, you dispatch the click event to all elements under the click.
Here is a very basic demo (click on the blue circle, the red circle or the intersection):
let clicked;
d3.select(".blue").on("click", function() {
if (!clicked) return;
console.log("blue circle were clicked")
});
d3.select(".red").on("click", function() {
if (!clicked) return;
console.log("red circle were clicked")
});
d3.select("svg").on("click", function() {
clicked = true;
getAllElements(...d3.mouse(this));
clicked = false;
function getAllElements(x, y) {
const elements = [];
let thisElement = document.elementFromPoint(x, y);
while (thisElement && thisElement.nearestViewportElement) {
elements.push(thisElement);
d3.select(thisElement).style("display", "none");
thisElement = document.elementFromPoint(x, y);
}
elements.forEach(function(elm) {
d3.select(elm).style("display", null)
.dispatch("click");
});
};
})
.as-console-wrapper {
max-height: 30% !important;
}
<script src="https://d3js.org/d3.v5.min.js"></script>
<svg>
<circle cx="100" cy="75" r="60" fill="powderblue" stroke="gray" stroke-width="2" opacity="0.75" class="blue"></circle>
<circle cx="170" cy="75" r="60" fill="tomato" stroke="gray" stroke-width="2" opacity="0.75" class="red"></circle>
</svg>
Here is how you can calculate the overlap area calculate clientX for each click event and make sure it is overlap area as you have already provide X and Y for your circles. Here is example. In example, I have provided a rough idea you can calculate according to your actual dimesions.
$(".circle").click(function(e) {
if((event.clientX>50 && event.clientX<80) && (event.clientY>25 && event.clientY<85)){
alert('overlaper area');
}
});
.path {
fill: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<svg width="525" height="226">
<circle class="circle" id="circle1" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
<circle class="circle" id="circle2" cx="80" cy="50" r="40" stroke="black" stroke-width="3" fill="transparent" />
</svg>

SVG pause/play Can not figure out why this isn't working...?

I need code to work just like on this page.
Play and pausing of an SVG. I went into inspect and pulled all the code I could, which seemed to be HTML. I could not see or find CSS or Javascript. Not sure if that is normal.
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="80 0 1024 768" onload="t=setInterval(updateTimer, 100)">
<script>
var time = 0;
function updateTimer() {
//document.getElementById("t").textContent = document.documentElement.getCurrentTime().toFixed(0) + "s";
}
function pause() {
time = document.documentElement.getCurrentTime();
document.documentElement.pauseAnimations();
clearInterval(t);
}
function play() {
if(time > 0)
document.documentElement.setCurrentTime(time);
clearInterval(t);
t=setInterval(updateTimer, 100);
document.documentElement.unpauseAnimations();
}
function stop() {
time = 0;
clearInterval(t);
document.documentElement.setCurrentTime(0);
document.documentElement.pauseAnimations();
}
</script>
<linearGradient id="grad">
<stop stop-color="rgb(10%,80%,10%)" offset="0"/>
<stop stop-color="rgb(10%,40%,20%)" offset="0.4"/>
<stop stop-color="rgb(10%,90%,30%)" offset="0.7"/>
<stop stop-color="rgb(10%,50%,40%)" offset="1"/>
</linearGradient>
<rect fill="url(#grad)" width="0%" height="50" x="100" y="300" rx="5">
<animate attributeName="width" to="100%" begin="0s" dur="30s"/>
</rect>
<text id="t" style="font:24px Arial Black;fill:white;stroke:black" transform="translate(100 334)"/>
<animateTransform type="translate" attributeName="transform" xlink:href="#t" begin="1s" dur="29s" from="100 334" to="1024 334"/>
<g transform="translate(100 500)">
<!-- Play -->
<g onclick="play()">
<rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5"/>
<path id="play" d="M12 5l20 15l-20 15Z" fill="white" pointer-events="none"/>
</g>
<!-- Pause -->
<g transform="translate(50 0)">
<rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="pause();"/>
<path id="pause" d="M14 10l0 20M26 10l0 20" stroke="white" fill="none" stroke-width="8" pointer-events="none"/>
</g>
<!-- Stop (rewind and pause) -->
<g transform="translate(100 0)">
<rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="stop()"/>
<rect x="10" y="10" width="20" height="20" fill="white" pointer-events="none"/>
</g>
</g>
</svg>
When I attempt playback on Code pen, the SVG plays but buttons don't work. At all. I thought the "onclick" would do it...?
Is this because the JS isn't accessible/applied? I don't see any "DIV" or "DOM" so I assume its not a CSS thing...
I have a basic knowledge of HTML, less of CSS and know NOTHING about JavaScript
Short version: getCurrentTime & setCurrentTime must be called on the SVG node.
const mySvg = document.getElementById("mySvg")
function updateTimer() {
const t = `${mySvg.getCurrentTime().toFixed(0)}s`;
document.getElementById("t").textContent = t;
}
function setCurrentTime(t) {
mySvg.setCurrentTime(t)
}
function pause() {
mySvg.pauseAnimations()
}
function play() {
mySvg.unpauseAnimations()
}
function stop() {
clearInterval();
setCurrentTime(0);
mySvg.pauseAnimations()
updateTimer();
}
<svg id="mySvg" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" viewBox="80 0 1024 768" onload="t=setInterval(updateTimer, 100)">
<linearGradient id="grad">
<stop stop-color="rgb(10%,80%,10%)" offset="0"/>
<stop stop-color="rgb(10%,40%,20%)" offset="0.4"/>
<stop stop-color="rgb(10%,90%,30%)" offset="0.7"/>
<stop stop-color="rgb(10%,50%,40%)" offset="1"/>
</linearGradient>
<rect fill="url(#grad)" width="0%" height="50" x="100" y="300" rx="5">
<animate attributeName="width" to="100%" begin="0s" dur="30s"/>
</rect>
<text id="t" style="font:24px Arial Black;fill:white;stroke:black" transform="translate(100 334)"/>
<animateTransform type="translate" attributeName="transform" xlink:href="#t" begin="1s" dur="29s" from="100 334" to="1024 334"/>
<g transform="translate(100 500)">
<!-- Play -->
<g onclick="play()">
<rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5"/>
<path id="play" d="M12 5l20 15l-20 15Z" fill="white" pointer-events="none"/>
</g>
<!-- Pause -->
<g transform="translate(50 0)">
<rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="pause();"/>
<path id="pause" d="M14 10l0 20M26 10l0 20" stroke="white" fill="none" stroke-width="8" pointer-events="none"/>
</g>
<!-- Stop (rewind and pause) -->
<g transform="translate(100 0)">
<rect width="40" height="40" rx="10" stroke="black" fill-opacity="0.5" onclick="stop()"/>
<rect x="10" y="10" width="20" height="20" fill="white" pointer-events="none"/>
</g>
</g>
</svg>
Long version: After all that, why wasn't it working in Codepen?
I can see that the link you posted is to an SVG document with it's own inline JavaScript (in the script tag).
The script calls some SVGElement methods on the SVG root element with document.documentElement.pauseAnimations();.
But what exactly is document element?
Document.documentElement returns the Element that is the root element of the document (for example, the element for HTML documents).
Because this code was called inside an SVG document, document.documentElement returns the SVG root node. However, because codepen is an HTML document, document.documentElement will return the HTML root node.
And you can't call methods like pauseAnimations() on an HTML root node because the HTML root node doesn't understand those methods.
So modern browsers can display SVG documents, HTML documents (and more) but here's the kicker: SVG documents can live inside of HTML documents.
You can see how document.documentElement could refer to two potential things depending on what type of document the JavaScript code was run from.

SVG in HTML: How to use a multicolored SVG as a mask

I know how to use SVG masks to completely "cut out" the mask in another shape, if the mask is monochrome.
How can I use a multicolored SVG definition X as the mask so that the outer shape of X defines the "hole" to be cut out?
Here are three images that illustrate what I am trying to achieve:
svg #1 to be used as mask
svg #2 on which the outer shape of #1 should be used as a cut-out
result
Creating a white-filled version of the shape as #enxaneta proposed is not applicable to my problem, as I have many "complicated" external SVG definitions, and I don't want to change every single one of them.
Is there another, simpler way to achieve what I want?
You need to define your paths with no fill. Then you use your paths for the mask and fill them with white. To draw the image you fill those paths with the colors of your choice.
svg{border:1px solid; width:49vw}
svg:nth-child(2){background:red;}
mask use{fill:white;}
<svg viewBox="0 0 100 50">
<defs>
<polygon id="a" points="30,5 70,20 75,40 20,20" />
<circle id="b" cx="50" cy="25" r="15" />
<circle id="c" cx="60" cy="35" r="10" />
<mask id="m">
<use xlink:href="#a"/>
<use xlink:href="#b"/>
<use xlink:href="#c"/>
</mask>
</defs>
<g id="complexShape">
<use xlink:href="#a" fill="lightblue" />
<use xlink:href="#b" fill="gold"/>
<use xlink:href="#c" fill="red"/>
</g>
</svg>
<svg viewBox="0 0 100 50">
<rect width="100" height="50" style="mask: url(#m)" />
</svg>
The colour of a mask determines the final opacity of the masked object at that point. The R, G, B, and A components of the mask colour are combined in a formula to determine a luminance value that is used to set the final transparency that the mask will be a that point. So, for example, if the mask is red, the final masked result will be semi transparent.
There is no way to make a coloured object be a solid (not translucent) mask. Only full white will do that.
Update
Assuming you have an external SVG image that looks like the following:
<svg viewBox="0 0 100 50">
<polygon id="a" points="30,5 70,20 75,40 20,20" fill="lightblue"/>
<circle id="b" cx="50" cy="25" r="15" fill="gold"/>
<circle id="c" cx="60" cy="35" r="10" fill="red" stroke="blue" stroke-width="4"/>
</svg>
You can turn this into a "mask" version by adding three lines to the start of your SVG.
<svg viewBox="0 0 100 50">
<filter id="blacken"><feFlood flood-color="black"/><feComposite operator="in" in2="SourceGraphic"/></filter>
<style>svg :not(#maskbg) { filter: url(#blacken); }</style>
<rect id="maskbg" x="-100%" y="-100%" width="300%" height="300%" fill="white"/>
<polygon id="a" points="30,5 70,20 75,40 20,20" fill="lightblue"/>
<circle id="b" cx="50" cy="25" r="15" fill="gold"/>
<circle id="c" cx="60" cy="35" r="10" fill="red" stroke="blue" stroke-width="4"/>
</svg>
This is something that could easily be scripted. This method should work for almost all SVGs.
Once you have all the mask variants built, you can apply them using mask-image.
https://developer.mozilla.org/en-US/docs/Web/CSS/mask-image

CSS style addition has stopped javascript function from working

I created this javascript function to change the colour of guitar string in an SVG. Originally, the SVG had 'stroke' colours defined in the markup and at that point the function worked, so that when I pressed the button, the colour of the string 'e-low' changed.
However, I decided I wanted to add CSS default style to the stroke colour (which you can see at the stop of the code) because I intend to have functionality so that when the button is pressed a second time, the colour returns to the default colour defined in the style section. Since I've added this, and changed the colour in the SVG to 'None', the javascript function has stopped working and the colour doesn't change whatsoever, and I don't know why.
Before I added the css style element
function svgMod() {
var s = document.getElementById("e-low");
s.setAttribute("stroke", "#000000");
}
#e-string,
#b-string,
#g-string,
#d-string,
#a-string,
#e-low {
stroke: #adad8b;
}
<svg xmlns="http://www.w3.org/2000/svg" ......... <path id="e-string" stroke="none" fill="none" stroke-width="2" d="M502.583,13.046v411.966" />
<path id="b-string" stroke="none" fill="none" stroke-width="2.5" d="M472.366,13.046v411.966" />
<path id="g-string" stroke="none" fill="none" stroke-width="3" d="M440.134,13.046v411.966" />
<path id="d-string" stroke="none" fill="none" stroke-width="3.3" d="M405.887,13.046v411.966" />
<path id="a-string" stroke="none" fill="none" stroke-width="3.5" d="M373.655,13.042v411.965" />
<path id="e-low" stroke="none" fill="none" stroke-width="4" d="M341.423,13.046v411.966" />
</svg>
<button class="btn" onclick="svgMod(); return false;">Test 1</button>
Make sure you have the right viewBox and a proper sizing for the SVG element, I just added a random viewBox to see the guitar strings.
You can read more about viewBox in this link
The viewBox attribute allows you to specify that a given set of
graphics stretch to fit a particular container element.
Also as #CBroe mentioned using s.style.stroke = '#000000' fits better to modify the styles of a element.
function svgMod() {
var s = document.getElementById("e-low");
s.style.stroke = "#000000";
}
#e-string,
#b-string,
#g-string,
#d-string,
#a-string,
#e-low {
stroke: #adad8b;
}
<svg xmlns="http://www.w3.org/2000/svg" width="210" viewBox="0 0 600 600">
<path id="e-string" stroke="none" fill="none" stroke-width="2" d="M502.583,13.046v411.966"/>
<path id="b-string" stroke="none" fill="none" stroke-width="2.5" d="M472.366,13.046v411.966"/>
<path id="g-string" stroke="none" fill="none" stroke-width="3" d="M440.134,13.046v411.966"/>
<path id="d-string" stroke="none" fill="none" stroke-width="3.3" d="M405.887,13.046v411.966"/>
<path id="a-string" stroke="none" fill="none" stroke-width="3.5" d="M373.655,13.042v411.965"/>
<path id="e-low" stroke="none" fill="none" stroke-width="4" d="M341.423,13.046v411.966"/>
</svg>
<button class="btn" onclick="svgMod(); return false;">Test 1</button>

Interacting with a .svg image

I have an image in the format .svg like the one below.
I want to make a webpage where the user can interact with a image like this, but with more nodes. The structure will be similar to a tree.
Is it possible to interact with this .svg image directly, using javascript/html/css?
If so, how?
Note: By interact I mean being able to click on the nodes -and the webpage recognizing it- and when one node is selected the color of the other nodes change.
Note2: I just have the .svg file, I don't know if I'm able to define this as a inline svg on html.
Note3: This image will have many nodes (80+), so I would rather not having to define a clickable area for each one of them and so on... But if this is the only solution, no problem.
Edit:
Here is the content of my .svg file:
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN"
"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
<!-- Generated by graphviz version 2.38.0 (20140413.2041)
-->
<!-- Title: g Pages: 1 -->
<svg width="134pt" height="116pt"
viewBox="0.00 0.00 134.00 116.00" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<g id="graph0" class="graph" transform="scale(1 1) rotate(0) translate(4 112)">
<title>g</title>
<polygon fill="white" stroke="none" points="-4,4 -4,-112 130,-112 130,4 -4,4"/>
<!-- a -->
<g id="node1" class="node"><title>a</title>
<ellipse fill="none" stroke="black" cx="27" cy="-90" rx="27" ry="18"/>
<text text-anchor="middle" x="27" y="-86.3" font-family="Times New Roman,serif" font-size="14.00">a</text>
</g>
<!-- b -->
<g id="node2" class="node"><title>b</title>
<ellipse fill="none" stroke="black" cx="27" cy="-18" rx="27" ry="18"/>
<text text-anchor="middle" x="27" y="-14.3" font-family="Times New Roman,serif" font-size="14.00">b</text>
</g>
<!-- a->b -->
<g id="edge1" class="edge"><title>a->b</title>
<path fill="none" stroke="black" d="M27,-71.6966C27,-63.9827 27,-54.7125 27,-46.1124"/>
<polygon fill="black" stroke="black" points="30.5001,-46.1043 27,-36.1043 23.5001,-46.1044 30.5001,-46.1043"/>
</g>
<!-- c -->
<g id="node3" class="node"><title>c</title>
<ellipse fill="none" stroke="black" cx="99" cy="-18" rx="27" ry="18"/>
<text text-anchor="middle" x="99" y="-14.3" font-family="Times New Roman,serif" font-size="14.00">c</text>
</g>
<!-- b->c -->
<g id="edge2" class="edge"><title>b->c</title>
<path fill="none" stroke="black" d="M54,-18C56.6147,-18 59.2295,-18 61.8442,-18"/>
<polygon fill="black" stroke="black" points="61.9297,-21.5001 71.9297,-18 61.9297,-14.5001 61.9297,-21.5001"/>
</g>
</g>
</svg>
The SVG would need to be inline to have interaction on a page. If you embed an image then the image (.svg) is treated as a single object. For the inline SVG each node should have a separate ID if you want to select them individually.
Here's one I created for another answer.
svg {
display: block;
width: 20%;
margin: 25px auto;
border: 1px solid grey;
stroke: #006600;
}
#buttons polygon:hover {
fill: orange;
}
#buttons rect:hover {
fill: blue
}
#center {
fill: #00cc00;
}
#top {
fill: #cc3333;
}
#right {
fill: #663399;
}
#left {
fill: #bada55;
}
<svg viewbox="0 0 100 100">
<g id="buttons">
<rect id="center" x="25" y="25" height="50" width="50" />
<polygon id="top" points="0,0 100,0 75,25 25,25" />
<polygon id="right" points="100,0 75,25 75,75 100,100" />
<polygon id="bottom" points="0,100 25,75 75,75 100,100" />
<polygon id="left" points="0,0 25,25 25,75 0,100" />
</g>
</svg>
You don't necessarily need to have the svg inline, you could have it in an object tag.
So the html would look like...
<div id="svgdiv">
<object id="svgobject" data="objectclicktest.svg"></object>
</div>
and correspending js
var mySvg = document.getElementById("svgobject").contentDocument.querySelectorAll('svg');
var myNodes = mySvg[0].querySelectorAll('.node');
for( var i = 0; i < myNodes.length; i++ ) {
myNodes[i].addEventListener('click', changeStyle );
}
function changeStyle() {
this.style.fill="blue";
}
Example Click on letters and they should go blue. Note, (I don't think this would work in a setup like a fiddle though)
inline svg elements can interact like other html elements, you can set css rules on them and apply js on them too, you dont need areas
svg is a markup language, meaning that you can use css selector libraries such as jquery to interact with the given svg. You can query the svg in order to get an element by its id, or get an array of elements selected by class. You can attach event handlers to them such as click, mouseover, mouseenter, etc. You can even style them with css.

Categories