When i add a JavaScript element to my SVG file it disapears - javascript

I am using snapsvg to manipulate my SVG file created with Inkscape.
When i try to add a rectangle from snapsvg to my already existing svg i get a blank page. You can see a example how i manipulate the svg.
I tried to make a new script section but it always but the rectangle or the element either above or under my svg. And i want it to be inside my svg.
//Run script right away
window.onload = function () {
var s = Snap("#iconDiv");
//Load SVG file
Snap.load("lager2.svg", function(f) {
//Load Rectangles and elements
Element1 = f.select("#Element1");
Group1 = f.select("#Group1");
//manipulate my rectangle
Group1.hover(function() {
Element1.attr({
fill: "red"
});
});
});
}
The only error message that i get is this one:
Uncaught TypeError: s.circle is not a function
at window.onload

Is the element #iconDiv a div, as the name suggests?
The getting started docs for Snap.svg says
First lets create our drawing surface out of existing SVG element
So you need to change your line of code accordingly:
var s = Snap("#iconDiv"); // Target a <div> won't work
to
var s = Snap("#iconSvg"); // Target the <svg> element instead

Related

Access current position in svg using javascript

I want to access current position that defined in variables. After that I want to make the element of that position was colored automatically when I load the page. The problem is I don't know how to access that defined position and append the color to html when its load.
I've try it in this, but it gets nothing colored when I load the page. Maybe my code was wrong and can anyone help?
https://jsfiddle.net/ax47kvu5/1/
var gigi = "P15";//id of g
var posisi = "C";//id of polygon
var kondisi = "amf";
if(kondisi=="amf"){
var group = $('polygon').parentNode().attr(gigi);
group.attr(posisi).css({fill: "#333333"});
$('polygon').html('XX');
}
https://jsfiddle.net/9n9jack8/ - In your example you didn't load jQuery, this is the first issue.$("#P15").find("#C").css({fill: "#333333"});

jQuery remove or hide all svg on the canvas

I want to remove or hide the svg I double click on.
var draw = SVG('output').size(1000, 500);
var table = draw.circle(50)
.fill('#00ff0000')
.stroke('black')]
.center(50, 50);
table.attr("class", "table");
$("svg").on('dblclick',function(event){
$(".table").hide();
});
var desk = draw.rect(50,50)
.fill('green')
.stroke('black')
.move(100,0);
desk.attr("class", "desk");
$("svg").on('dblclick',function(event){
$(".desk").hide();
});
var chair = draw.rect(50,50)
.fill('green')
.stroke('black')
.move(200,0);
desk.attr("class", "chair");
$("svg").on('dblclick',function(event){
$(".chair").hide();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/svg.js/2.6.3/svg.min.js"></script>
<div id="output"></div>
I want to hide the one that I double click on, but now the result is that, all of them are hidden if I double click any one of them. Even if I double click the blank space of canvas, all of the SVG images are also hidden.
When you write $("svg"), that targets every single svg element on the page.
When this code runs $("svg").on('dblclick',function(event){ $(".table").hide(); }); for example,
every SVG on the page gets the "dblclick" event to hide ".table". To solve this, instead of globally selecting all svg elements, use CSS selectors https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectors to only grab the svg related to the class you give it (e.g. maybe you want $("svg.table").on('dblclick') or something like that)

How to append an svg loaded by d3.xml into an svg

Trying to load external svgs in to a dynamically created svg but still access the properties of the loaded svgs. That is why I'm using d3.xml but haven't figured out how to integrate it in to the dynamic svg created with d3.
Code and js console here
The code produces this svg
<svg id = "svgObj">
<g class = "grp"></g>
<g class = "grp"></g>
</svg>
I'm trying to load circle.svg within each element so it looks like this
<svg id = "svgObj">
<g class = "grp"><svg id=minus>...</svg></g>
<g class = "grp"><svg id=minus>...</svg></g>
</svg>
I tried the code below but console errors that there is no appendChild method
var grps = d3.selectAll( "g" );
img = grps.appendChild( svgNode.cloneNode( true ) );
Thanks ahead
As #helderdarocha explained, you're mixing up your d3 methods with your plain Javascript methods. That answer gave you how to do it with plain Javascript methods, I'll balance that out by explaining how to do it with d3 methods.
To append a new element within each element of a d3 selection, the method name is simply append, not appendChild. The parameter to append is either a tag name (for which d3 creates a new element of that type for each element in the selection) or a function that returns an actual DOM element (the function will get called for each element in the selection with the data value and index as parameters). Since you're cloning an existing node, that's the version you want to use:
var grps = d3.selectAll( "g" );
img = grps.append( function(){return svgNode.cloneNode( true );} );
I haven't used D3 before but it seems easy to understand. The error message says that Array has no appendChild() method. I read the documentation and discovered that the selections return as double nodes (see Operating on selections) so you would have to add [0][0] (which would select the first node) to be able to use appendChild().
This selects the first node using plain DOM and produces no error (and draws a partial shape on the output):
var grps = d3.selectAll( "g" )[0][0];
Since you need to insert code in each node, you can use each() (see Control) like this:
d3.selectAll( "g" ).each(function() {
img = this.appendChild( svgNode.cloneNode( true ) );
});
I tested it on your code and it produces a black circle with a white dash in the middle. Is that what you expected?

Load SVG into a specific div with Snap SVG

What is the correct way to load an SVG file into a specific div using SnapSVG?
Following the documentation I have this JS:
var s = Snap();
Snap.load("fox.svg", function (f) {
s.append(f.select("g#fox"));
});
This loads the SVG just above the body tag, however if I try to set it's location, nothing happens, there is no error. This is what I have attempted so far:
var s = Snap('#myDiv');
Where am I going wrong?
This should work, its not far removed from your example, so its hard to tell whats wrong with yours without a live example and the svg to look at.
If you want to upload a fiddle or something, it may help.
var s = Snap("#svgdiv");
var l = Snap.load("path.svg", onSVGLoaded ) ;
function onSVGLoaded( data ){
s.append( data );
}
Edit: Just to extend on Duopixels answer, the element you are trying to add, should be an svg element (ie
<svg id="mysvgtoload">...</svg> // you can add an svg to a div
<g id="mygrouptoload">...</g> // you can't add this to a div, but could to an svg element
in the file) or add the element (g or path or whatever) to an existing svg tag/element in your html. I suspect you may be trying to add a element direct to a div, which won't work, but its hard to tell without the file.
Also double check that Snap is loaded fine, and you can do a console.log( data ) in the function to check that it has loaded the markup correct.

Removing an SVG element from the DOM using jQuery

I'm using jQuery to add an element to an embedded SVG like this:
var rect = SVG('rect');
$(rect).attr( { x: left,
y: top,
width: right - left,
height: bottom - top,
style: style } );
$(parentElement).append(rect);
parentElement could be for example $('g:first', svgRoot), where svgRoot refers to the embedded SVG element.
function SVG(elementName) {
return document.createElementNS('http://www.w3.org/2000/svg', elementName);
}
This works well, the new rectangle is shown in the browser and added to the DOM:
However, removing this rectangle fails. It is still shown in the browser and present in the DOM:
$(rect).remove();
I also tried
rect.parentNode.removeChild(rect);
which results in the error message "Uncaught TypeError: Cannot call method 'removeChild' of null".
Do you have any idea how I can fix that?
Using jQuery SVG or another plugin/framework is not possible in my project.
I ended up solving this problem using groups.
I ended up with this code :
var group = getGroupByName(name);
group.parentNode.removeChild(group);
...
function getGroupByName(name) {
var container = document.getElementById("container");
var groups = container.getElementsByTagName("g");
for(var i=0; i<groups.length; i++) {
if(groups[i].getAttributeNS(null, "name") === name) {
return groups[i];
}
}
return null;
}
Where container is my main SVG element.
This is tried and true. Works properly.
EDIT
As pointed out in the comments. You can find this fiddle that works. Similar to your example. It creates 4 rectangles and removes the 2 first ones.
If you want to remove the first element you have to specify this :
$("rect").first().remove();
Or if you want to do something with ALL of your rectangles you could approach this with something of the sort :
$("rect").each(function() {
... //could remove them here
}
Edit 2
According to last comment, as long as you have the reference to the object, you can use it's variable to remove it.
This updated fiddle will show you that using lastRect you can remove this last rectangle that was added.
I found that doing a .find("*") helped a lot, I'm guessing it flattens the DOM out and thus ignores any nesting complexities that jQuery can't handle (perhaps... this is my theory at least).
So for example this removes anything other than rect, g, svg elements.
$("svg").find("*").not("rect, g").remove();
A jSFiddle showing find() and removing svg elements

Categories

Resources