tags:

views:

26

answers:

2

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.

+1  A: 

Try this:

$('rect#Y6').click( function(){
  alert('hello');
});
Ken Redler
It didn't work either, Ken. I appreciate the help though. The control was rendered like this: <rect style="fill:black;fill-opacity:0.78488375;stroke:black;stroke-width:0.04082483;stroke-miterlimit:1;stroke-opacity:0.78488375;stroke-dasharray:none" id="Y6" width="20" height="20" x="120.44141" y="32.362183" class="wz-flat" label=""></rect>
Hallaghan
@Hallaghan, it seems to work here: http://jsfiddle.net/YcV3c/.
Ken Redler
Now, that's quite strange. Using firebug, I notice that when I'm loading the page, it enters the click event correctly. But upon clicking the rectangle, nothing really happens and the event is never fired. Do you have any clue? EDIT: If you want to see my jquery code or know any details about my files, I will add them in my comment.
Hallaghan
@Hallaghan, sure. Without the code it's hard to say what's going wrong.
Ken Redler
@Ken: I've edited my main post to reflect my script.
Hallaghan
+1  A: 

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

robertc
Thanks Robert, after trying to write as you suggested, it worked! Thanks a lot!
Hallaghan