How to make svg <circle> clickable [closed]

426
December 10, 2016, at 1:16 PM

As title! I want <circle> can be click use javascript onclick event or JQuery. But i don't know How to do?

Here's my code


Thanks!

Answer 1

Here's your EXACT code in a snippet NOT in jsbin.com

It works

Other answers do have tips on how to use jquery if you want to go that path

I would recommend jquery over using onclick attribute, far more flexible

<!DOCTYPE html> 
<html> 
<head> 
  <meta charset="utf-8"> 
  <title>JS Bin</title> 
</head> 
<body> 
<svg height='600' width='820'> 
   
 <script> 
   function test(){ 
     alert("yyyy") 
   } 
 </script>  
   
<circle onclick="test()" cx="20" cy="30" fill="black" r="20"></circle> 
</svg> 
</body> 
</html>

Answer 2

Try this

HTML

<svg height="100" width="100">
  <circle cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" id='circ' />
</svg>

JS

$(document).ready(function(){
   $('#circ').click(function(){
      alert('clicked') ;
   });
});
Answer 3

Your code works perfectly on my Chrome but not on Firefox. So just add a semi-colon ; at the end of your alert. Change it to: alert("yyyy");

Update:

The code is fine on jsbin. It doesn't work until you click Run with JS

Answer 4

I found your problem just tick Auto-run js in output window in jsbin.

Or you can press

Run with js

Answer 5

As I commented above your code works fine,there is no issue in it.

A way to get click event on circle using jquerycan be done like this. You should avoid using inline events.read here

$('circle').on("click",function(){ 
  console.log($(this).attr("cy"));//30 
 test();//your function getting called on click of circle.  
  })
    
<!DOCTYPE html> 
<html> 
<head> 
  <meta charset="utf-8"> 
  <title>My Circle</title> 
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"> </script> 
</head> 
<body> 
<svg height='600' width='820'> 
   
 <script> 
   function test(){ 
     alert("yyyy"); 
   } 
 </script>  
   
<circle  cx="20" cy="30" fill="black" r="20"></circle> 
</svg> 
</body> 
</html>

Rent Charter Buses Company
READ ALSO
Join query issue in jquery datatable

Join query issue in jquery datatable

I am using jquery datatable with server-side processingJust I am trying to make join query to produce output

334
Disable jquery script for mobile devices

Disable jquery script for mobile devices

I would like to disable following script when the website is opened in mobile device, because i don't want unnecesary animations:

437
send() is an anonmyous function?

send() is an anonmyous function?

iam testing ajax on a wamp server but its saying that send() is an anonmyous function and iam getting blank document

346
Table Overflow Fixed Horizontal Scrollbar

Table Overflow Fixed Horizontal Scrollbar

I have a table with a fixed initial columnIs it possible to have a horizontal scrollbar that is always visible when the table overflows vertically?

429