angryip angryip - 1 year ago 53
jQuery Question

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:

.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");

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?

Answer Source

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');

And then, you call it:


Here is the fiddle, using SVG elements: