Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why jQuery.data() bugs with Raphael svg paths?

I have a problem with jQuery .data() and Raphael's SVG path().

I wrote a little example to explain.

paper = Raphael(0, 0, 600, 600)
polygon = paper.path('M19,20L24,83L106,62L112,23Z')
polygon.data('test', 'I need this info later!')
polygon.attr({"fill":"orange"})

$(document).on('click', onClick)

function onClick() {
    console.log('click')
    if(event.target.nodeName === 'path') {
        // how do i get data('test') ?

        // console.log(this.data('test')) // Uncaught TypeError: Object #<HTMLDocument> has no method 'data' 
        console.log($(this).data('test')) // undefined
        // console.log(event.target.data('test')) // Uncaught TypeError: Object #<SVGPathElement> has no method 'data' 
        console.log($(event.target).data('test')) // undefined

        // But jquery.remove() does work?
        $(event.target).remove()

    }
}

As you can see, I made a polygon, filled it with a color, and added an event listener to the document. On every click I check the target. If this is a polygon, I want to get its data.

Notice that in my real code, I generate tons of polygons like this. So a simple polygon.data() won't help. My only solution is using the event.target as reference. Example of multiple polygons

How can I receive the data values?

like image 587
Ron van der Heijden Avatar asked Jan 28 '26 11:01

Ron van der Heijden


1 Answers

You were close, you just need the node wrapped in a jquery object to set the data first:

$(polygon.node).data('test', 'I need this info later!');

I updated your jsfiddle to show it working.

like image 164
Neil Avatar answered Jan 30 '26 00:01

Neil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!