angryip
angryip

Reputation: 2300

Jquery cannot invoke a click, but can manually do it with a mouse

I am using D3 to create a map that holds some text objects scattered around. Each of the text objects has an ID attribute appended to it and some words for its value. Here is some sample code to understand what I am creating:

g.selectAll("text")
    .data(data).enter()
    .append("text")
    .attr("id", function(d,i){return "cows_name";})
    .text( function(d) { return "cows"; })
    .on("click", function(d) {
        alert("### we are in here" with $(this).attr("id"));
    })

When I manually click the "cows" text boject in my browser (Firefox 45), the alert event is called, and I am able to conclude that the id attribute retuns back "cows_name".

However, when I try to invoke this JQuery code in either Selenium or Scratchpad:

var toClick = $("#cows_name")
toClick.click();

Nothing happens at all. Is there something I am missing in understaning what is the correct way to "click" D3 objects that are generated using my above script?

Upvotes: 2

Views: 86

Answers (2)

Gerardo Furtado
Gerardo Furtado

Reputation: 102219

First, let's change your toClick to:

var toClick = $("#cow_name")[0];

This selects the actual DOM element. After changing your toClick, I found this cool function to "simulate" click events:

function fakeClick(target) {
    var event = new Event('click');
    target.dispatchEvent(event);
};

And then, you call it:

fakeClick(toClick);

Here is the fiddle, using SVG elements: https://jsfiddle.net/ap1m1L0q/4/

Upvotes: 2

Kld
Kld

Reputation: 7078

You can use jQuery .trigger()

var toClick = $("#cows_name");
toClick.trigger( "click" );

Upvotes: 1

Related Questions