Clicking a link with Javascript

I have a webpage which contains FAQs. http://www.rcda.org/Offices/parish_services/FAQs.html

When the questions are clicked, they expand an answer. I’ve been asked to link to the page from another and to display the answer for a specific question. Rather than force users to locate the correct question and click it, I’d like to display the answer on load.

Is there any javascript that will allow me to simulate the mouse click on a particular link?

I think that might be a security issue; imagine someone with malicious intent injecting code into a page that, upon load, clicks a link to a page with malicious code. Of course, the same thing could be achieved with a meta tag, methinks. And I know jQuery has .click(), but I’ve never used it, before.

However, I’m assuming that URL parameters are going to be used to indicate the desired FAQ. One could set up JavaScript that will not “hide” the desired answer (showing the answer upon page load instead of simulating a link click.) One could also use JavaScript to scroll to said answer. Would this be a sufficient workaround?

HTH,

:slight_smile:

I’d start by adding an ID to all the FAQ links, so you can refer to the correct one in a URL, eg /FAQs.html#hotlines

Then you just need a little JS to check for a hash in the URL (the part starting with #) and use jQuery to simulate a click on the link with the matching ID:

if (location.hash) {
  $(location.hash).click();
}

I found a solution that works. I originally didn’t think any of the solutions I found would because people said that not all browsers support .click(). I then noticed that those postings were a few years old and support for .click() has become almost universal.

solution:
I gave the link an ID=“papal”
I then check for the existence of #papal at the end of the URL, click if present.

    function actuateLink(link)
    {
            var allowDefaultAction = true;
           
        if (link.click)
        {
           link.click();
           return;
        }
        else if (document.createEvent)
        {
           var e = document.createEvent('MouseEvents');
           e.initEvent(
              'click'     // event type
              ,true      // can bubble?
              ,true      // cancelable?
           );
           allowDefaultAction = link.dispatchEvent(e);           
        }
              
        if (allowDefaultAction)       
        {
           var f = document.createElement('form');
           f.action = link.href;
           document.body.appendChild(f);
           f.submit();
        }
    }
    
    function init(){
    	
    	//alert(window.location.href );
    	var URL = window.location.href
    	var n = URL.indexOf("#papal");
    	//alert(n);
    	if (n > 0) {
    		actuateLink(document.getElementById('papal'));		
    	}
     }

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.