[EDIT: This was a really dumb question, a string of small mistakes made me believe that there was some magic. But there is no magic at all. I didn't correct anything below, because then the answer would not make sense. I have no idea why some people on the internet say that the script must be inside the svg element and things like that. There is just nothing different with svg elements as any other DOM elements.]
How can I dynamically set event handlers on SVG objects? It seems that I can define a static onclick handler in the SVG source, but once it is rendered, if I try and add the onclick handler later, it will even destroy the one that was statically set, but it will not set a new one.
I know jquery can do this, so what is the secret here? I don't want jquery and all the answers I have found were talking about jquery. How is it done in pure javascript?
<html>
<head>
<title>France</title>
<script type="text/javascript">
function clickHandler() {
console.log(this, ...arguments);
}
</script>
</head>
<body>
<svg style="width:512px; height:512px;">
<g>
<path
d="M444.48,172.62l-0.64,1.78l-0.58,-0.31l-0.49,-1.72l0.4,-0.89l1.0,-0.72l0.3,1.85ZM429.64,147.1l1.78,1.58l1.46,-0.13l2.1,1.42l1.35,0.27l1.23,0.83l3.04,0.5l-1.03,1.85l-0.3,2.12l-0.41,0.32l-0.95,-0.24l-0.5,0.43l0.06,0.61l-1.81,1.92l-0.04,1.42l0.55,0.38l0.88,-0.36l0.61,0.97l-0.03,1.0l0.57,0.91l-0.75,1.09l0.65,2.39l1.27,0.57l-0.18,0.82l-2.01,1.53l-4.77,-0.8l-3.82,1.0l-0.53,1.85l-2.49,0.34l-2.71,-1.31l-1.16,0.57l-4.31,-1.29l-0.72,-0.86l1.19,-1.78l0.39,-6.45l-2.58,-3.3l-1.9,-1.66l-3.72,-1.23l-0.19,-1.72l2.81,-0.61l4.12,0.81l0.47,-0.48l-0.6,-2.77l1.94,0.95l5.83,-2.54l0.92,-2.74l1.6,-0.49l0.24,0.78l1.36,0.33l1.05,1.19ZM289.01,278.39l-0.81,0.8l-0.78,0.12l-0.5,-0.66l-0.56,-0.1l-0.91,0.6l-0.46,-0.22l1.09,-2.96l-0.96,-1.77l-0.17,-1.49l1.07,-1.77l2.32,0.75l2.51,2.01l0.3,0.74l-2.14,3.96Z"
fill="#3cb44b" fill-opacity="1" stroke="none"
onclick="clickHandler.apply(this, arguments);">
</path>
</g>
<script type="text/javascript">
(function() {
const path = document.querySelector('path');
console.log(path.onclick);
path.onclick="clickHandler.apply(this, arguments);";
})()
</script>
</svg>
<script type="text/javascript">
(function() {
const path = document.querySelector('path');
console.log(path.onclick);
path.onclick="clickHandler.apply(this, arguments);";
})()
</script>
</body>
</html>
CodePudding user response:
The value of the onclick
property needs to be a function, not a string.
You're overwriting the existing click handler, but since the value isn't valid, it doesn't do anything.
path.onclick = clickHandler;