Duck
Duck

Reputation: 36013

Javascript - clicking an image using code

I have an image on a page. I cannot change the page. When you click on the images this page has, a function run and processes the image. The image is not a button. To make the image respond to clicks, the page developer added a listener to it. In fact, every image on that page has a listener. The listener is listening the "img" tag.

When you click on an image, the Javascript checks to see if that image should respond to a click and then runs or not a function.

I am developing some automation to fill the form where this image is. This automation script needs to fill the form and click on that image. How do I click on that image using javascript?

What should I look on the code to discover the method that runs when the image is clicked?

My problem is this: as the listener is attached to all images on that page but just some respond to the clicks, I suppose that the function attached to the listener has to receive a reference to the image that needed to be process... this is what complicates everything...

If you guys want, I can zip the page and the javascripts and put it here.

thanks

Upvotes: 0

Views: 3389

Answers (2)

Eric Fortis
Eric Fortis

Reputation: 17360

http://jsfiddle.net/efortis/9nmAR/

$(document).ready(function (){
    $('img').click(function() {
        alert($(this).attr('alt'));     
    });


$('img').eq(0).click();     // << I think this is what you need

});

Upvotes: 2

Digital Plane
Digital Plane

Reputation: 38294

Dispatch a click event:

var target = yourImage;  //<--(insert your image here);
if(document.createEvent) {
  //Normal W3C event model
  var clickEvent = document.createEvent("MouseEvents");
  clickEvent.initMouseEvent("click", true, true, window, 
    0, 0, 0, 0, 0, false, false, false, 0, null);
  target.dispatchEvent(clickEvent);
}
else {
  //IE event model
  target.fireEvent("onclick");
}

Normally, clicks are attached to an element using element.addEventListener and element.attachEvent, but sometimes element.onclick is used.
If the page uses jQuery, it might use the live method, which attaches to the root node. However, the previous method should work correctly since the event's target is set to target.

Upvotes: 2

Related Questions