Search code examples
javascriptjquerysvgraphaeljquery-events

Simulate click event on raphael js path


I have 4 SVG with multiple paths. I have a copy on this SVG in a different panel (this svg is not clickable). When I click on the clickable SVG path I fill the path with a different color.

I created a button to import all paths colored on the first SVG into the second SVG. For that I have to simulate a click event on the good paths. To find the matched path I'm using the attribute d= of the path.

Here is my code to add event on each path :

function buildEvent(regions, area) {
    for(var regionName in regions) {
        (function (region) {
            region.attr(style);
            region.node.name = regionName;
            region.data('clicked', false);

        region[0].addEventListener("mouseover", function() {
            if (!region.data('clicked')) region.animate(hoverStyle, animationSpeed);
        }, true);

        region[0].addEventListener("mouseout", function() {
            if (!region.data('clicked')) region.animate(style, animationSpeed);
        }, true);

        region[0].addEventListener("click", function() {
            if (region.data('clicked')) {
                region.attr("fill", "#ddd");
                region.data('clicked', false);
                json_data[area][region.node.name] = false;
            }else{
                region.attr("fill", "#A8BED5");
                region.data('clicked', true);
                json_data[area][region.node.name] = true;
            }
        }, true);

        })(regions[regionName]);
    }
}

And here is my code when I click on the import button

$('#btn-import').on('click', function() {

    $('.tab-pane.active svg path').each(function () {
        if ($(this).attr('fill') == '#A8BED5') {
            var to_fill = $("#form svg path[d='" + $(this).attr('d') + "']");

            // to_fill.trigger('click');
            // to_fill[0].trigger('click');
            // to_fill.click();
            to_fill[0].click();
        }
    });
});

As you can see I tried 4 ways to trigger my click event. I don't understand why the click event isn't triggered. to_fill variable is the good object I think because I can get the fill attribute of my path if I did :

console.log(to_fill.attr('fill') // output #dddddd

Solution

  • I solved my problem. I replaced this line :

    region[0].addEventListener("click", function() {
    

    By this line :

    region.node.onclick = function () {
    

    And now I can use to_fill.trigger('click'); or to_fill.click();