2

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!

Ezeeroc
  • 185
  • 2
  • 4
  • 14

2 Answers2

3
$(".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);
Paul LeBeau
  • 97,474
  • 9
  • 154
  • 181
0

try this

jQuery('body').on('click','.circle',function(){
 alert('clicked')
})
Bai Nguyen
  • 814
  • 7
  • 16