user4329628 user4329628 - 2 years ago 77
Javascript Question

Trigger an 'onClick' via URL, but do not visit that URL

Trying to launch a click event of

.register-btn a
nav item when visiting a given URL, but not allow the browser to visit that URL.

So, would remain on ( or redirect to if I must ), and proceed to activate the click of a button.

This is what I have so far, which redirects nowhere as that ended up taking longer than the click event, and it also was quite messy having to load the 404, then wait, then redirect, then wait, then wait for the click event.

I would like something clean and smooth if possible.

jQuery(document).ready(function() {
jQuery(function() {
switch (window.location.pathname) {
case '/memberlogin':
jQuery('.register-btn a').trigger( "click" );
return False;

Probably explained it dreadfully so apologies all - the
.register-btn a
already exists so I can't create this element, I simply wish to trigger the click for it when visiting a URL/link. Open to suggestions but I assumed something like /memberlogin would suffice, then the link would trigger. The snag is I don't want to "visit" that URL, but use it for the trigger only.

Open to an easier way and tell me if I am asking for something that doesn't work, just figured there must be a way.

Answer Source

A full javascript solution is (snippet updated as asked):

window.onload = function () {
  []'.dontGo')).forEach(function(element, index) {
    element.addEventListener('click', function(e) {
    }, false);

  // in order to target a specific URL you may write code like in reported,
  // assuming the result is only one element,
  // otherwise you need to use the previous []
  document.querySelectorAll('.dontGo[href=""]')[0].addEventListener('click', function(e) {
    alert('Linkedin anchor: ' +;
  }, false);
<a href="" class="dontGo"> stackoverflow </a><br/>
<a href="" class="dontGo"> google </a><br/>
<a href="" class="dontGo"> linkedin </a><br/>
<a href="" class="dontGo"> twitter </a><br/>

The querySelector let you select elements in a lot of different ways: if you need to select an anchor with a specific href value you can write:


Remember, always, that the result of querySelectorAll is a NodeList array. You can test against the length of such array in order to get, just for instance, only the second element if it exists, like:

 var nodEles = document.querySelectorAll('.dontGo[href=""]');
    if (nodEles.length > 1) {

or you can use the format:


to convert the NodeList to a normal array and than apply the event listener for each element.

Yes, you may prefix the href attribute of anchor tag with an hash (#) to avoid page redirecting. But, in this case, the hash tag is used to jump in another page section and this will change your url.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download