title: PhantomJS click on an image and wait for load
body: <p>I'm trying to do page automation with PhantomJS. My goal is to be able to go to a website, click an image, and continue with other code once the page has loaded from the click. To test this I'm trying to write a script that will go to the url of the quick start guide on the PhantomJS website and then click on the PhantomJS logo bringing the page to the PhantomJS homepage. Also to render a picture of the website before and after the click to make sure the click worked. This is my current code:</p>
  
  <pre><code>var page = require('webpage').create();
  
  page.open('http://phantomjs.org/quick-start.html', function(status) {
  console.log(status);
  page.render('websiteBeforeClick.png');
  console.log(page.frameUrl); //check url before click
  
  var element = page.evaluate(function() {
    return document.querySelector('img[alt="PhantomJS"]');
  });
  
  page.sendEvent('click', element.offsetLeft, element.offsetTop, 'left');
  
  window.setTimeout(function () {
  console.log(page.frameUrl); //check url after click
  }, 3000);
  
  console.log('element is ' + element); //check that querySelector() is returning an element
  page.render('websiteAfterClick.png');
  phantom.exit();
  });
  </code></pre>
  
  <p>Problem is my before and after pictures are the same. This is my output when I run it.</p>
  
  <pre><code> success
   element is [object Object]
  </code></pre>
  
  <p>Im using their sendEvent method from here "<a href="http://phantomjs.org/api/webpage/method/send-event.html" rel="nofollow">http://phantomjs.org/api/webpage/method/send-event.html</a>" but I'm not sure if its working.</p>
  
  <p>Also why doesnt the console.log(page.frameUrl) in my window.setTimeout() get executed?</p>
  
  <p>I was looking at their page automation examples on the PhantomJS website. Particularly this one "<a href="https://github.com/ariya/phantomjs/blob/master/examples/imagebin.js" rel="nofollow">https://github.com/ariya/phantomjs/blob/master/examples/imagebin.js</a>".
  I noticed their examples used</p>
  
  <pre><code>document.querySelector('input[name=disclaimer_agree]').click()
  </code></pre>
  
  <p>But when I tried it with my code I got an error.</p>
  
  <pre><code>document.querySelector('img[alt="PhantomJS"]').click();
  TypeError: 'undefined' is not a function
  </code></pre>
  
  <p>EDIT#1:</p>
  
  <p>I changed the end section of my code to this:</p>
  
  <pre><code>page.sendEvent('click', element.offsetLeft, element.offsetTop, 'left');
  
  
  window.setTimeout(function () {
    console.log(page.frameUrl);
    page.render('websiteAfterClick.png');
    phantom.exit();
  }, 3000);
  
  console.log('element is ' + element);
  });
  </code></pre>
  
  <p>Now my after image is correct. But now my question is, If I want to continue on with my code i.e. click on another element on the site, will my new code have to be all nested inside of the timeout function?</p>