Q&A Categories

  • No categories

How to perform a click on a html element from the code (programatically) with the same effect as the user would ?

Nov

16

2012

I need to perform a click on an html element like a link or a form button which would have the same effect as it would if the used would click it.
This is useful when having client forms which have to be automatically submitted when the used performs some certain actions or an ajax call needs the page to be submitted.

In: Uncategorized Asked By: [nuxx] (Anonymously)
vote
Answer #1

I also had a problem like this on a personal project I worked in the past. the most cases I needed this is when you have to post a checkout form or any form as a matter of fact after you get an asynchronous ajax call behind the scenes – like a validation of some sort.
Using this approach, if you have any special behavior (javascript, jQuery etc.) triggered when the click is performed, it will be, since the click is simulated correctly.

Here’s the java script code which does the magic:


function fakeClick(event, elementObj) {
  if (elementObj.click) {
       elementObj.click()
  } else if(document.createEvent) {
       if(event.target !== elementObj) {
	      var evt = document.createEvent("MouseEvents"); 
	      evt.initMouseEvent("click", true, true, window, 
	          0, 0, 0, 0, 0, false, false, false, false, 0, null); 
	      var allowDefault = elementObj.dispatchEvent(evt);
	}
   }
}


Answers Answered By: alin [ Grey Star Level]

Answer this Question

Enter name & email to post an Answer. You can also Login / Join us

For a better management of this site please consider Logging in / Joining us before posting a Question. It makes everithing easier for us.

Please enter the captcha code bellow.
Logged in users don't have to use captchas. Don't have an account? Join us!

 

Link Exchange:

You can add url to the best of the internet directory. Our url is added under Reference Directory
HE Blog Directory WEB LOG SHOWWEB LOG SHOW