Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Click event for SVG rectangle

Tags:

jquery

svg

I'm using SVG together with jQuery in my Mvc Application. I draw a series of rectangles on my page and what I would like to do is attach a click or mouseover event for each rectangle, for say, popup an alert box. I've tried something like this, so far:

$("rect[id='Y6']").attr('onclick', function() { alert("Hello!") });

and

$("rect[id='Y6']").live('click', function() {    
    alert("Hello!");
};

But sadly none of this events really worked for this control. Does anyone know how to do this?

EDIT:

I'm adding the javascript code I'm using below:

<script type="text/javascript">
    /*function resetSize(svg, width, height) {
        svg.configure({ width: width || $(svg._container).width(),
            height: height || $(svg._container).height()
        });
    }*/
    function onLoad(svg, error) {
        //svg.text(10, 20, error || 'Loaded into ' + this.id);
        //resetSize(svg, null, null); //'100%', '100%');
    }

    $(function() {
        $('#layout').svg({});

        var svg = $('#layout').svg('get');
        svg.load('<%= Url.Action("Layout", new{ id = Model.Id }) %>', { //<%= Url.Content("~/media/svg/lion.xml") %>', {
            addTo: false,
            changeSize: false,
            onLoad: onLoad
        });
    });    

$('rect#Y6').click( function(){
  alert('hello');
});

</script>

The rectangles are loaded from a svg picture.

like image 874
Hallaghan Avatar asked Oct 29 '10 16:10

Hallaghan


2 Answers

Your code to add the click handler needs to be part of the onLoad function - with that change it works for me.

like image 174
robertc Avatar answered Oct 16 '22 09:10

robertc


Try this:

$('rect#Y6').click( function(){
  alert('hello');
});
like image 25
Ken Redler Avatar answered Oct 16 '22 07:10

Ken Redler