Reputation: 178
I am creating some circles dynamically in svg and I want to add an onlick
function to all of them. I know that it can be done like this: <rect class="btn" x="0" y="0" width="10" height="10" onclick="alert('click!')" />
, but I am creting the elements like this:
newCircle.setAttribute("class","circle");
newCircle.setAttribute("cx",centerX);
newCircle.setAttribute("cy","850");
newCircle.setAttribute("r","150");
newCircle.style.stroke = "black";
newCircle.style.strokeWidth = "2px";
newCircle.style.opacity = circleOpacity[i-1];
newCircle.style.fill = circleColour[i];
svgNode.appendChild(newCircle);
I tried adding this,
$(".circle").click(function() {
onclick= "alert('click!')";
})
but it doesnt work.
I also tried something like this:newCircle.setAttribute("onclick","myFunction");
How can I make it work? Thank you!
Upvotes: 2
Views: 2667
Reputation: 101956
$(".circle").click(function() { onclick= "alert('click!')"; })
This should have been
$(".circle").click(function() {
alert('click!');
})
newCircle.setAttribute("onclick","myFunction");
This should have been
newCircle.setAttribute("onclick","myFunction()");
But, these days, the normal way to do this is as follows:
newCircle.addEventListener("click", myFunction);
Upvotes: 3
Reputation: 834
try this
jQuery('body').on('click','.circle',function(){
alert('clicked')
})
Upvotes: 0