Compose unique svg appending multiple svgObject from external files - javascript

I try to compose a unique HTML file composed by the concat of multiple svg, loads from externals file. I've create a function that receive in input the content of SVG file and want to append it to an svg child node already load in the dom.
function LoadComponent(xmlContent) {
//the node name to append svg
var gridCell = "Zone00";
//svgDoc is
var itemGrid = svgDoc.getElementById(gridCell)
if (itemGrid != null)
{
var oParser = new DOMParser();
var oDOM = oParser.parseFromString(xmlContent, "image/svg+xml");
var root = oDOM.documentElement;
alert(itemGrid);
itemGrid.appendChild(root);
}
else
{
alert("item not found");
return false;
}
return true;
}
My Idea is to create a Grid into the principal svg, and Load in the cells other svg from external files. After all I want to animate the controls using SVG animations.
The loading does not work properly.
Thanks

Related

how to apply a style by printing svg from javascript

by printing svg from javascript I got my chart without styles.css. Any ideas how to add styles?
function print(){
var element = document.getElementById("chart");
var serializer = new XMLSerializer();
var view = serializer.serializeToString(element);
console.log(view);
var printWin = window.open('','','left=0;top=0;width=800;height=600;toolbar=0;scrollbars=0; status=0;');
printWin.document.write(view);
printWin.document.close();
printWin.print();
printWin.close();
}
if want to know what I mean check this screenshot http://de.tinypic.com/r/30auvec/5
I need somehow to point on my styles.css file which is located not in the same file

Access SVG DOM / 'g' Elements Created in Adobe Illustrator

I am trying to access the SVG DOM that has a variety of adobe illustrator (layered) elements within the SVG file. Ideally, I would align the HTML slider range number (1-100) with a individual 'g' elements and animate, hide, show when that range number is reached as the user engages with the slider.
Please see github project:
https://github.com/EdBrooks/media-stroke
$(document).ready(function() {
var input = document.getElementsByTagName('input')[0];
var svg = $('#svgFile').svg({loadURL: 'img/media_stroke.svg'});
for (i=0; i < svg.length; i++) {
var g = document.getElementsByTagName('g');
var g1 = [{0:g}];
console.log(g1);
// var g1 = document.getElementById('group1').style.visibility = "hidden";
// var re = [{0:g}];
// console.log(re);
}
function InputVal() {
this.number =
$('input');
var change = input.addEventListener('change', function() {
var value = this.value
console.log(value);
if (value == 23) {
alert('wow dumb')
}
}, false);
}
InputVal();
});
It looks like you want to perform manipulation on SVG elements and do some animation.. for that you can use library like Snap.svg which is similar to jQuery for HTML Dom!
Check out it's getting started page (look for section 15)
or watch video

How to display image from another page in my page

I want to start a greasemonkey plugin to an existing page. The plugin should fetch and display some images automatically, each image from different pages.
I thought of using jQuery.get("link", function(data)) and hide the page and display the images only but on an average to display 4 images I should load 6 webpages into present webpage it is creating a delay in loading.
Is there any other work around to create a function that loads the page html of all image pages in background or in another tab and get the href of <a> tag's in that page, into my page and load only images into my page?
You can try this solution below.
Just put the URLs you want in the "pages" array. When the script runs, it makes Ajax calls in the background. When they are ready, it searches the source returned for images and picks one randomly. If found, it wraps the image in a link to the page where it found it (or if available, the image's url) and inserts the linked image to the top of the body of your own current page.
You can try the code by pasting it into your browser's JavaScript console and it will add the images to the current page.
You also see a demo here: http://jsfiddle.net/3Lcj3918/3/
//pages you want
var pages =
[
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random',
'https://en.wikipedia.org/wiki/Special:Random'
]
//a simple function used to make an ajax call and run a callback with the target page source as an argument when successful
function getSubPageSource(url, successCallback)
{
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if (xhr.readyState == 4 && xhr.status == 200)
{
//when source returned, run callback with the response text
successCallback(xhr.responseText);
}
};
//requires a proxy url for CORS
var proxyURL = 'https://cors-anywhere.herokuapp.com/';
xhr.open('GET', proxyURL+url, true);
//set headers required by proxy
xhr.setRequestHeader("X-Requested-With","XMLHttpRequest");
xhr.setRequestHeader("Access-Control-Allow-Origin","https://cors-anywhere.herokuapp.com/");
xhr.send();
}
//a function that extract images from given url and inserts into current page
function injectImagesFrom(url)
{
getSubPageSource(url, function(data)
{
//trim source code to body only
var bodySource = data.substr(data.indexOf('<body ')); //find body tag
bodySource = bodySource.substr(bodySource.indexOf('>') + 1); //finish removing body open tag
bodySource = bodySource.substring(0, bodySource.indexOf('</body')); //remove body close tag
//create an element to insert external source
var workingNode = document.createElement("span");
//insert source
workingNode.innerHTML = bodySource;
//find all images
var allImages = workingNode.getElementsByTagName('img');
//any images?
if (allImages.length > 0)
{
//grab random image
var randomIndex = Math.floor(Math.random() * allImages.length);
var randomImage = allImages.item(randomIndex);
//add border
randomImage.setAttribute('style', 'border: 1px solid red;');
//restrain size
randomImage.setAttribute('width', 200);
randomImage.setAttribute('height', 200);
//check if parent node is a link
var parentNode = randomImage.parentNode;
if (parentNode.tagName == 'A')
{
//yes, use it
var imageURL = parentNode.getAttribute('href');
}
else
{
//no, use image's page's url
var imageURL = url;
}
//add a link pointing to where image was taken from
var aLink = document.createElement("a");
aLink.setAttribute('href', imageURL);
aLink.setAttribute('target', '_blank');
//insert image into link
aLink.appendChild(randomImage);
/* INSERT INTO PAGE */
//insert image in beginning of body
document.body.insertBefore(aLink,document.body.childNodes[0]);
//remove working node children
while (workingNode.firstChild) {
workingNode.removeChild(workingNode.firstChild);
}
//unreference
workingNode = null;
}
});
}
for (var ii = 0, nn = pages.length; ii < nn; ii++)
{
injectImagesFrom(pages[ii]);
}

Don't load scripts appended with innerHTML?

I'm appending a whole HTML page to a div (to scrape). How do I stop it from requesting script, and css files ? I tried immediately removing those nodes but they still get requested.
It's for a browser addon, I'm scraping with JS
As #adeneo wrote you don't have to add the html to a page in order to scrape information from it, you can turn it into DOM tree that is disconnected from the page DOM and process it there.
In jQuery it is simple $("html text here"). Then you can scrape it using the API,
eg.
function scrape_html(html_string) {
var $dom = $(html_string);
var name = $dom.find('.name').text();
return name;
}
without jQuery:
function scrape_html(html_string) {
var container = document.createElement('div');
container.innerHTML = html_string;
var name = container.getElementsByClassName('name')[0].innerText;
return name;
}
Setting the innerHTML of a temporary HTML element that has not been added to the document, will not execute scripts, and since it does not belong to your document, the style will not be applied either.
This will give you an opportunity to strip out any unwanted elements before copying the innerHTML to your own document.
Example:
var temp = document.createElement('div');
temp.innerHTML = html; // the HTML of the 'other' page.
function removeElements(element, tagName)
{
var elements = temp.getElementsByTagName(tagName);
while(elements.length > 0)
{
elements[0].parentNode.removeChild(elements[0]);
}
}
removeElements(temp, 'script');
removeElements(temp, 'style');
removeElements(temp, 'link');
container.innerHTML = temp.innerHTML;

Loading JSON and filling SVG depends on data

I want to fill a country depends on how many users are online from this country. I have SVG file which has all countries, and the if for example from Canada I have 5 people online, then script should fill id="ca to green.
I storage the Data in a JSON formatted file.
The error I get in the Console is:
TypeError: svgMap is undefined
var mapElement = svgMap.getElementById(iso).style.fill="#94d31b";
$(document).ready(function()
{
$.getJSON("results.json", function(data)
{
data = data.iso_countries;
var map = document.getElementById("blank_map");
var svgMap = map.contentDocument;
for(var key in data)
{
var iso = data[key].country;
var visitors = data[key].visitors;
if( visitors > 1 && 50>=visitors)
{
var mapElement = svgMap.getElementById(iso).style.fill="#94d31b";
}
else if( visitors > 50 && 500>=visitors)
{
document.getElementById("iso").style.fill="#94d31b";
}
}
});
});
It is possible you will have an easier time if you use d3.js to generate an SVG instead of JQuery. See this example, similar to what you would like to do. http://bl.ocks.org/mbostock/5912673
Your need NameSpace for javascript, to handle tags to append new tags o update tags
function Text(){
//svg is a google chart
var svg = document.getElementById('graphic').getElementsByTagName('svg')[0];
var parent = svg.contentDocument;
//show me structure svg as DOM
console.log(parent);
//find tag fill and change color and write element type text
for(var i=0; i<svg.childNodes[4].childNodes[1].childNodes[1].childElementCount; i++) {
var g = document.createElementNS('http://www.w3.org/2000/svg', 'g');
var text = document.createElementNS('http://www.w3.org/2000/svg', 'text');
var child = svg.childNodes[4].firstChild.nextSibling.firstChild.nextSibling.firstChild;
text.setAttribute('x', child.getAttribute('x'));
text.setAttribute('y', child.getAttribute('y'));
text.setAttribute('fill', '#000000');
text.setAttribute('dy', '-2');
text.textContent = 'Hell0';
parent.removeChild(child);
g.appendChild(child);
g.appendChild(text);
parent.appendChild(g);
}
}
I hope that it help you

Categories

Resources