Calling Javascript Function From Svg File
Solution 1:
Different things are happening here. First the solution to your problem:
<scriptlanguage="JavaScript"src="http://code.jquery.com/jquery-2.1.0.min.js"></script><scriptlanguage="JavaScript">
$(document).ready(function () {
loadSVGasXML();
});
functionloadSVGasXML() {
varSVGFile="myfile.svg";
var loadXML = newXMLHttpRequest();
functionhandler(){
var svgDiv = document.getElementById("svgDiv");
if(loadXML.readyState == 4 && loadXML.status == 200) {
var xmlString=loadXML.responseText;
svgDiv.innerHTML=xmlString;
$("a").click(function() {
alert('hi');
});
fitSVGinDiv();
}
}
if (loadXML != null) {
loadXML.open("GET", SVGFile, true);
loadXML.onreadystatechange = handler;
loadXML.send();
}
}
functionfitSVGinDiv(){
var divWH=60;
var mySVG=document.getElementsByTagName("svg")[0];
var bb=mySVG.getBBox();
var bbw=bb.width;
var bbh=bb.height;
//--use greater of bbw vs bbh--if(bbw>=bbh)
var factor=bbw/divWH;
elsevar factor=bbh/divWH;
var vbWH=divWH*factor;
var vbX=(bbw-vbWH)/2;
var vbY=(bbh-vbWH)/2;
mySVG.setAttribute("viewBox",vbX+" "+vbY+" "+vbWH+" "+vbWH);
mySVG.setAttribute("width","100%");
mySVG.setAttribute("height","100%");
}
</script><!--<a href="#crisp"> hi </a>--><divid="svgDiv"></div><br><br><aid="crisp"> hello</a></div>
Now the explanation:
$("a").click(function() {
alert('hi');
});
What it does, more and less, is to look for all the <a>
html elements that is in your web right now and bind to them the onclick event to say "hi" to everybody.
At the beging there is no svg and so there is no "a" elements and you do the binding. Then the svg is loaded by loadSVGasXML();
and the html content is changed. New tags are added. But this tags are attached to the web page after to bind the event width $("a").click(function() {alert('hi'});
and so this new onclick events haven't been binded yet. So what you need to do is to make the event bind whenever you change your web content dynamically after everything is loaded. So you need to place the binding inside the handler callback function.
Second you are using an old way to get the DOM. document.all.svgDiv
it dates from a dark times before the Roman Empire (just joking) where to develop anything related to the web was a pain in the ass. In those wretched times every browser got's they own way to access the DOM. In our situation this is the way used long time ago to access the DOM object in IE. Fortunately nowadays everything have changed to better and there are better ways to access the DOM which are supported by all the browsers. If you want to access a DOM element by an id using raw javascript i suggest you to always use document.getElementById("svgDiv");
.
Finally it comes the loadXML.status
. When the request have been successful the status is 200 not 0.
Probably those lasts you may already know it and are just a copy & paste mistake. Just pointing to it. Wish this may be helpful to you.
Post a Comment for "Calling Javascript Function From Svg File"