Apoorv
Apoorv

Reputation: 620

Copy SVG from inside a hidden div to create a thumbnail

I have a page where i am rendering some charts. These are fusion charts. I have a grid layout where each grid box is clickable and on click the divs in which the charts are rendered are shown. By default these divs are hidden and once the respective anchor tag is clicked the corresponding chart is shown. Now what i want is that the grid boxes should have a resized thumbnail image of the chart that is being rendered. i am trying to copy the svg but i cant since it seems i cannot copy content from a hidden div. Below is the piece of code i am mainly interested in.

 $("#testButton").on('click',function (){
    var testDiv = $("#chart-container").clone();
    console.log($(testDiv.html()))
    var testSvg = $(testDiv.html()).find('svg').clone();

testSvg.appendTo($("#testDiv"))
})

If you notice in the above code only when the div $("#chart-container") is shown it works. Otherwise i am not able to copy the svg element. What i would want is that when the charts are loaded in the hidden divs the corresponding grid boxes should have a thumbnail of their resized svgs.

In the i have provided only the first grid box contains a chart rest contain some text https://jsfiddle.net/nyb4v4og/.

Any help would be appreciated

Upvotes: 0

Views: 345

Answers (1)

Peter Collingridge
Peter Collingridge

Reputation: 10979

You should use find on the div, not the html contents of the div. Try var testSvg = $(testDiv).find('svg').clone(); You shouldn't need to clone the chart contents if you're going to clone the svg anyway.

$("#testButton").on('click',function (){
    var testSvg = $("#contents").find('svg').clone();
    testSvg.appendTo($("#target"))
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="hidden-source" style="display:none;">
	<div id="contents">
		<svg width="100" height="40"><text x="10" y="25">Test</text></svg>
	</div>
</div>

<div id="target"></div>
<div id="testButton">Test button</div>

Upvotes: 1

Related Questions