Rectangle 27 2

Yes, your problem is with div.onclick = here you are actually assigning a click action to your div! Which will execute when your page loads.

div.addEventListener('click' function(){});

@mauguerra then your going to have to post a jsfiddle like Jonathan said. Because something is off in your code. The above should work.

html - onclick function executes without any click on javascript - Sta...

javascript html javascript-events onclick
Rectangle 27 73

You shouldn't be using onClick any more if you are using jQuery. jQuery provides its own methods of attaching and binding events. See .click()

$(document).ready(function(){
    var js = "alert('B:' + this.id); return false;";
    // create a function from the "js" string
    var newclick = new Function(js);

    // clears onclick then sets click using jQuery
    $("#anchor").attr('onclick', '').click(newclick);
});

That should cancel the onClick function - and keep your "javascript from a string" as well.

The best thing to do would be to remove the onclick="" from the <a> element in the HTML code and switch to using the Unobtrusive method of binding an event to click.

Using onclick = function() { return eval(js); } doesn't work because you are not allowed to use return in code passed to eval().

onclick = eval("(function(){"+js+"})");
onclick = new Function(js);
Function()

Beware of this as well: jQuery unbind() vs removeAttr() see novogeek.com/post/2009/05/18/

JavaScript: changing the value of onclick with or without jQuery - Sta...

javascript jquery onclick attributes
Rectangle 27 20

Your code may work without document.ready() just be sure that your script is after the #clicker. Checkout this demo: http://jsbin.com/aPAsaZo/1/

The idea in the ready concept. If you sure that your script is the latest thing in your page or it is after the affected element, it will work.

<!DOCTYPE html>
<html>
<head>


<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
  <a href="#" id="clicker" value="Click Me!" >Click Me</a>
  <script type="text/javascript">

        $("#clicker").click(function () {
            alert("Hello!");
            $(".hide_div").hide();

        });


</script>

</body>
</html>
document.ready()

This is a better answer because the suggestion that the jquery script must be within a 'document.ready()' function is misleading. Yes, it's safer there, but if you set up the html element for a jquery function on the fly (such as query a table row depending on what button is clicked), it needs to be outside/after that function. I mistakenly changed the name of the target div for my pop-up overlays and then spent several frustrating hours looking for a script error. Big lesson learnt.

This is a wrong answer, cause the JS code should be in the head of the DOM and not inline. The fact that you spent several hours looking for the script error is not a JS problem, it's your problem not reading the docs properly and not knowing how to use debug tools.

@AndreyShipilov Who's said that, just look at the source of this page and go down to its bottom, you will see javascript code there.

@AndreyShipilov - do you know how to use debug tools to troubleshoot this issue? Then please share your knowledge with others instead of offending them. Try to be constructive and fair.

javascript - Why is this jQuery click function not working? - Stack Ov...

javascript jquery onclick click onclicklistener
Rectangle 27 20

Your code may work without document.ready() just be sure that your script is after the #clicker. Checkout this demo: http://jsbin.com/aPAsaZo/1/

The idea in the ready concept. If you sure that your script is the latest thing in your page or it is after the affected element, it will work.

<!DOCTYPE html>
<html>
<head>


<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
  <a href="#" id="clicker" value="Click Me!" >Click Me</a>
  <script type="text/javascript">

        $("#clicker").click(function () {
            alert("Hello!");
            $(".hide_div").hide();

        });


</script>

</body>
</html>
document.ready()

This is a better answer because the suggestion that the jquery script must be within a 'document.ready()' function is misleading. Yes, it's safer there, but if you set up the html element for a jquery function on the fly (such as query a table row depending on what button is clicked), it needs to be outside/after that function. I mistakenly changed the name of the target div for my pop-up overlays and then spent several frustrating hours looking for a script error. Big lesson learnt.

This is a wrong answer, cause the JS code should be in the head of the DOM and not inline. The fact that you spent several hours looking for the script error is not a JS problem, it's your problem not reading the docs properly and not knowing how to use debug tools.

@AndreyShipilov Who's said that, just look at the source of this page and go down to its bottom, you will see javascript code there.

@AndreyShipilov - do you know how to use debug tools to troubleshoot this issue? Then please share your knowledge with others instead of offending them. Try to be constructive and fair.

javascript - Why is this jQuery click function not working? - Stack Ov...

javascript jquery onclick click onclicklistener
Rectangle 27 20

Your code may work without document.ready() just be sure that your script is after the #clicker. Checkout this demo: http://jsbin.com/aPAsaZo/1/

The idea in the ready concept. If you sure that your script is the latest thing in your page or it is after the affected element, it will work.

<!DOCTYPE html>
<html>
<head>


<meta charset=utf-8 />
<title>JS Bin</title>
</head>
<body>
  <script src="http://code.jquery.com/jquery-latest.min.js"
        type="text/javascript"></script>
  <a href="#" id="clicker" value="Click Me!" >Click Me</a>
  <script type="text/javascript">

        $("#clicker").click(function () {
            alert("Hello!");
            $(".hide_div").hide();

        });


</script>

</body>
</html>
document.ready()

This is a better answer because the suggestion that the jquery script must be within a 'document.ready()' function is misleading. Yes, it's safer there, but if you set up the html element for a jquery function on the fly (such as query a table row depending on what button is clicked), it needs to be outside/after that function. I mistakenly changed the name of the target div for my pop-up overlays and then spent several frustrating hours looking for a script error. Big lesson learnt.

This is a wrong answer, cause the JS code should be in the head of the DOM and not inline. The fact that you spent several hours looking for the script error is not a JS problem, it's your problem not reading the docs properly and not knowing how to use debug tools.

@AndreyShipilov Who's said that, just look at the source of this page and go down to its bottom, you will see javascript code there.

@AndreyShipilov - do you know how to use debug tools to troubleshoot this issue? Then please share your knowledge with others instead of offending them. Try to be constructive and fair.

javascript - Why is this jQuery click function not working? - Stack Ov...

javascript jquery onclick click onclicklistener
Rectangle 27 63

If you have jQuery installed then why not just do this:

$('#proxyAnchor')[0].click();

Note that we use [0] to specify the first element. The jQuery selector returns a jQuery instance, and calling click() on that only calls click javascript handler, not the href. Calling click() on the actual element (returned by [0]) will follow the link in an href etc.

As to why your original code is not working - it is probably because you are calling onclick, and not onclick(). Without the parenthesis JavaScript will return whatever is assigned to the onclick property, not try to execute it.

Try the following simple example to see what I mean:

var f = function() { return "Hello"; };     
alert(f);
alert(f());

The first will display the actual text of the function, while the second will display the word "Hello" as expected.

For the use case of "follow the href defined in the anchor" this answer fails

@RoatinMarth Actually, it does work for that. Part of the problem is that you're using JSFiddle (Clicking the link itself doesn't work in JSFiddle). For a perfect example of it working in JSFiddle, try setting the target to _blank. Also, you didn't do [0]. I tested it without the target on my own server, and it worked just fine. So here's a "fixed" version for JSFiddle: jsfiddle.net/SNdHW/4/show

Can I get to set the path where the file should be downloaded? because using this it's just downloading to the DOWNLOADS folder. i want to to save to the location of html file.

jquery - JavaScript: Invoking click-event of an anchor tag from javasc...

javascript jquery click onclick
Rectangle 27 108

You are supposed to add the javascript code in a $(document).ready(function() {}); block.

$(document).ready(function() {
  $("#clicker").click(function () {
    alert("Hello!");
    $(".hide_div").hide();
  });
});

As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"

How stupid of me!! Still learning. I thought I click function doesn't need one since it's activated on clicking vs document.ready where it loads on page load.

@starbucks Don't worry about it too much, everyone makes mistakes, and especially when learning :)

The document ready function sets up the listeners based on what it finds on the page. If you don't do this, they are never set up. The best way to do this, however, is to delegate them with the "on()" function, instead. That way any elements added to the page after load will still work!

Also, with the "on" function, you don't actually need to use the document ready function. It sets the listener to document level, and then scrapes the page for the elements to listen to. That's why it's a little faster to be a little more specific about what element type you want to listen to, like "div.listentome" as opposed to ".listentome". Instead of checking every element for the "listentome" class, it checks only the divs, in this example.

@SeanKendle - That's not how .on() works. You can (optionally) use it to create delegated handlers, but either way it doesn't "scrape the page", it binds a listener to the specific element(s) in the jQuery object you call it on.

javascript - Why is this jQuery click function not working? - Stack Ov...

javascript jquery onclick click onclicklistener
Rectangle 27 108

You are supposed to add the javascript code in a $(document).ready(function() {}); block.

$(document).ready(function() {
  $("#clicker").click(function () {
    alert("Hello!");
    $(".hide_div").hide();
  });
});

As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"

How stupid of me!! Still learning. I thought I click function doesn't need one since it's activated on clicking vs document.ready where it loads on page load.

@starbucks Don't worry about it too much, everyone makes mistakes, and especially when learning :)

The document ready function sets up the listeners based on what it finds on the page. If you don't do this, they are never set up. The best way to do this, however, is to delegate them with the "on()" function, instead. That way any elements added to the page after load will still work!

Also, with the "on" function, you don't actually need to use the document ready function. It sets the listener to document level, and then scrapes the page for the elements to listen to. That's why it's a little faster to be a little more specific about what element type you want to listen to, like "div.listentome" as opposed to ".listentome". Instead of checking every element for the "listentome" class, it checks only the divs, in this example.

@SeanKendle - That's not how .on() works. You can (optionally) use it to create delegated handlers, but either way it doesn't "scrape the page", it binds a listener to the specific element(s) in the jQuery object you call it on.

javascript - Why is this jQuery click function not working? - Stack Ov...

javascript jquery onclick click onclicklistener
Rectangle 27 104

You are supposed to add the javascript code in a $(document).ready(function() {}); block.

$(document).ready(function() {
  $("#clicker").click(function () {
    alert("Hello!");
    $(".hide_div").hide();
  });
});

As jQuery documentation states: "A page can't be manipulated safely until the document is "ready." jQuery detects this state of readiness for you. Code included inside $( document ).ready() will only run once the page Document Object Model (DOM) is ready for JavaScript code to execute"

How stupid of me!! Still learning. I thought I click function doesn't need one since it's activated on clicking vs document.ready where it loads on page load.

@starbucks Don't worry about it too much, everyone makes mistakes, and especially when learning :)

The document ready function sets up the listeners based on what it finds on the page. If you don't do this, they are never set up. The best way to do this, however, is to delegate them with the "on()" function, instead. That way any elements added to the page after load will still work!

Also, with the "on" function, you don't actually need to use the document ready function. It sets the listener to document level, and then scrapes the page for the elements to listen to. That's why it's a little faster to be a little more specific about what element type you want to listen to, like "div.listentome" as opposed to ".listentome". Instead of checking every element for the "listentome" class, it checks only the divs, in this example.

@SeanKendle - That's not how .on() works. You can (optionally) use it to create delegated handlers, but either way it doesn't "scrape the page", it binds a listener to the specific element(s) in the jQuery object you call it on.

javascript - Why is this jQuery click function not working? - Stack Ov...

javascript jquery onclick click onclicklistener
Rectangle 27 11

Can I get to set the path where the file should be downloaded? because using this it's just downloading to the DOWNLOADS folder. i want to to save to the location of html file.

jquery - JavaScript: Invoking click-event of an anchor tag from javasc...

javascript jquery click onclick
Rectangle 27 3

mousedown/mouseup is indeed the only way you can get notified of middle button interaction, so detecting a down-then-up event without intervening mouseout event is more or less the best you can do. It's not very good.

I wouldn't bother, since even if you trapped this one eventuality, there are many other interactions you can't pick up. As well as middle-click (which might not be Open in new tab in all browser/configurations; for example in IE6 that'll be the user turning on scrolling mode), the user might right-click and Open in new window, or drag the link to the address bar or new tab, or various other browser-specific actions to perform a navigation.

Sorry! Can't be done. The HTML5 <a ping> attribute may in future allow you to detect a followed link at the server-side without having to go through a redirect as in Lee's answer, but you simply don't get script access to the many different types of navigation possible from the browser's interface.

javascript - jQuery: click handler is not invoked when link is opened ...

javascript jquery click onclick
Rectangle 27 17

I found the best solution for this problem by using ON with $(document).

$(document).on('click', '#yourid', function() { alert("hello"); });

for id start with see below:

$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });

finally after 1 week I not need to add onclick triger. I hope this will help many people

Ah thanks, the above didn't work for me, but this did! (probably some weird interaction with angular and routing)

Just like Flink, I also solved problem with this. Thanks.. 100 upvote..

javascript - Why is this jQuery click function not working? - Stack Ov...

javascript jquery onclick click onclicklistener
Rectangle 27 17

I found the best solution for this problem by using ON with $(document).

$(document).on('click', '#yourid', function() { alert("hello"); });

for id start with see below:

$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });

finally after 1 week I not need to add onclick triger. I hope this will help many people

Ah thanks, the above didn't work for me, but this did! (probably some weird interaction with angular and routing)

Just like Flink, I also solved problem with this. Thanks.. 100 upvote..

javascript - Why is this jQuery click function not working? - Stack Ov...

javascript jquery onclick click onclicklistener
Rectangle 27 17

I found the best solution for this problem by using ON with $(document).

$(document).on('click', '#yourid', function() { alert("hello"); });

for id start with see below:

$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });

finally after 1 week I not need to add onclick triger. I hope this will help many people

Ah thanks, the above didn't work for me, but this did! (probably some weird interaction with angular and routing)

Just like Flink, I also solved problem with this. Thanks.. 100 upvote..

javascript - Why is this jQuery click function not working? - Stack Ov...

javascript jquery onclick click onclicklistener
Rectangle 27 32

const element = document.querySelector('a');
element.addEventListener('click', event => event.preventDefault(), true);
element.addEventListener()
element.removeEventListener()
useCapture
  • Cares about semantics. Basically, it makes registering event handlers more explicit. For a beginner, a function call makes it obvious that something happens, whereas assigning event to some property of DOM element is at least not intuitive.
  • Allows you to separate document structure (HTML) and logic (JavaScript). In tiny web applications it may not seem to matter, but it does matter with any bigger project. It's way much easier to maintain a project which separates structure and logic than a project which doesn't.
  • Eliminates confusion with correct event names. Due to using inline event listeners or assigning event listeners to .onevent properties of DOM elements, lots of inexperienced JavaScript programmers thinks that the event name is for example onclick or onload. on is not a part of event name. Correct event names are click and load, and that's how event names are passed to .addEventListener().
  • Works in almost all browser. If you still have to support IE <= 8, you can use a polyfill from MDN.
const element = document.querySelector('a');
element.onclick = event => event.preventDefault();
<a href="//google.com">Try clicking this link.</a>

This was a way to register event handlers in DOM 0. It's now discouraged, because it:

  • Allows you to register only one event handler. Also removing the assigned handler is not intuitive, because to remove event handler assigned using this method, you have to revert onevent property back to its initial state (i.e. null).
  • Doesn't respond to errors appropriately. For example, if you by mistake assign a string to window.onload, for example: window.onload = "test";, it won't throw any errors. Your code wouldn't work and it would be really hard to find out why. .addEventListener() however, would throw error (at least in Firefox): TypeError: Argument 2 of EventTarget.addEventListener is not an object.
  • Doesn't provide a way to choose if you want to handle event in its capturing or bubbling phase.
<a href="//google.com" onclick="event.preventDefault();">Try clicking this link.</a>

Similarly to element.onevent, it's now discouraged. Besides the issues that element.onevent has, it:

  • Is a potential security issue, because it makes XSS much more harmful. Nowadays websites should send proper Content-Security-Policy HTTP header to block inline scripts and allow external scripts only from trusted domains. See How does Content Security Policy work?
  • If you generate your page with a server-side script, and for example you generate a hundred links, each with the same inline event handler, your code would be much longer than if the event handler was defined only once. That means the client would have to download more content, and in result your website would be slower.
EventTarget.addEventListener()
EventTarget.removeEventListener()

javascript - addEventListener vs onclick - Stack Overflow

javascript onclick addeventlistener
Rectangle 27 29

const element = document.querySelector('a');
element.addEventListener('click', event => event.preventDefault(), true);
element.addEventListener()
element.removeEventListener()
useCapture
  • Cares about semantics. Basically, it makes registering event handlers more explicit. For a beginner, a function call makes it obvious that something happens, whereas assigning event to some property of DOM element is at least not intuitive.
  • Allows you to separate document structure (HTML) and logic (JavaScript). In tiny web applications it may not seem to matter, but it does matter with any bigger project. It's way much easier to maintain a project which separates structure and logic than a project which doesn't.
  • Eliminates confusion with correct event names. Due to using inline event listeners or assigning event listeners to .onevent properties of DOM elements, lots of inexperienced JavaScript programmers thinks that the event name is for example onclick or onload. on is not a part of event name. Correct event names are click and load, and that's how event names are passed to .addEventListener().
  • Works in almost all browser. If you still have to support IE <= 8, you can use a polyfill from MDN.
const element = document.querySelector('a');
element.onclick = event => event.preventDefault();
<a href="//google.com">Try clicking this link.</a>

This was a way to register event handlers in DOM 0. It's now discouraged, because it:

  • Allows you to register only one event handler. Also removing the assigned handler is not intuitive, because to remove event handler assigned using this method, you have to revert onevent property back to its initial state (i.e. null).
  • Doesn't respond to errors appropriately. For example, if you by mistake assign a string to window.onload, for example: window.onload = "test";, it won't throw any errors. Your code wouldn't work and it would be really hard to find out why. .addEventListener() however, would throw error (at least in Firefox): TypeError: Argument 2 of EventTarget.addEventListener is not an object.
  • Doesn't provide a way to choose if you want to handle event in its capturing or bubbling phase.
<a href="//google.com" onclick="event.preventDefault();">Try clicking this link.</a>

Similarly to element.onevent, it's now discouraged. Besides the issues that element.onevent has, it:

  • Is a potential security issue, because it makes XSS much more harmful. Nowadays websites should send proper Content-Security-Policy HTTP header to block inline scripts and allow external scripts only from trusted domains. See How does Content Security Policy work?
  • If you generate your page with a server-side script, and for example you generate a hundred links, each with the same inline event handler, your code would be much longer than if the event handler was defined only once. That means the client would have to download more content, and in result your website would be slower.
EventTarget.addEventListener()
EventTarget.removeEventListener()

javascript - addEventListener vs onclick - Stack Overflow

javascript onclick addeventlistener
Rectangle 27 26

const element = document.querySelector('a');
element.addEventListener('click', event => event.preventDefault(), true);
element.addEventListener()
element.removeEventListener()
useCapture
  • Cares about semantics. Basically, it makes registering event handlers more explicit. For a beginner, a function call makes it obvious that something happens, whereas assigning event to some property of DOM element is at least not intuitive.
  • Allows you to separate document structure (HTML) and logic (JavaScript). In tiny web applications it may not seem to matter, but it does matter with any bigger project. It's way much easier to maintain a project which separates structure and logic than a project which doesn't.
  • Eliminates confusion with correct event names. Due to using inline event listeners or assigning event listeners to .onevent properties of DOM elements, lots of inexperienced JavaScript programmers thinks that the event name is for example onclick or onload. on is not a part of event name. Correct event names are click and load, and that's how event names are passed to .addEventListener().
  • Works in almost all browser. If you still have to support IE <= 8, you can use a polyfill from MDN.
const element = document.querySelector('a');
element.onclick = event => event.preventDefault();
<a href="//google.com">Try clicking this link.</a>

This was a way to register event handlers in DOM 0. It's now discouraged, because it:

  • Allows you to register only one event handler. Also removing the assigned handler is not intuitive, because to remove event handler assigned using this method, you have to revert onevent property back to its initial state (i.e. null).
  • Doesn't respond to errors appropriately. For example, if you by mistake assign a string to window.onload, for example: window.onload = "test";, it won't throw any errors. Your code wouldn't work and it would be really hard to find out why. .addEventListener() however, would throw error (at least in Firefox): TypeError: Argument 2 of EventTarget.addEventListener is not an object.
  • Doesn't provide a way to choose if you want to handle event in its capturing or bubbling phase.
<a href="//google.com" onclick="event.preventDefault();">Try clicking this link.</a>

Similarly to element.onevent, it's now discouraged. Besides the issues that element.onevent has, it:

  • Is a potential security issue, because it makes XSS much more harmful. Nowadays websites should send proper Content-Security-Policy HTTP header to block inline scripts and allow external scripts only from trusted domains. See How does Content Security Policy work?
  • If you generate your page with a server-side script, and for example you generate a hundred links, each with the same inline event handler, your code would be much longer than if the event handler was defined only once. That means the client would have to download more content, and in result your website would be slower.
EventTarget.addEventListener()
EventTarget.removeEventListener()

javascript - addEventListener vs onclick - Stack Overflow

javascript onclick addeventlistener
Rectangle 27 82

Interesting, this is probably a "feature request" (ie bug) for jQuery. The jQuery click event only triggers the click action (called onClick event on the DOM) on the element if you bind a jQuery event to the element. You should go to jQuery mailing lists ( http://forum.jquery.com/ ) and report this. This might be the wanted behavior, but I don't think so.

I did some testing and what you said is wrong, even if you bind a function to an 'a' tag it still doesn't take you to the website specified by the href attribute. Try the following code:

<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
 <script>
  $(document).ready(function() {
   /* Try to dis-comment this:
   $('#a').click(function () {
    alert('jQuery.click()');
    return true;
   });
   */
  });
  function button_onClick() {
   $('#a').click();
  }
  function a_onClick() {
   alert('a_onClick');
  }
 </script>

</head>
<body>
 <input type="button" onclick="button_onClick()">
 <br>
 <a id='a' href='http://www.google.com' onClick="a_onClick()"> aaa </a>

</body>
</html>

It never goes to google.com unless you directly click on the link (with or without the commented code). Also notice that even if you bind the click event to the link it still doesn't go purple once you click the button. It only goes purple if you click the link directly.

I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.

I tried your code, and it does exactly as you said it does, but my code does as I described above. I'll do some more experiments and see if I can put together a simple example of my results that you can try.

Ok. It must have been something I did wrong. I was absolutely certain at the time I posted my question that it was working, but since I tried your example mine no longer works. I'll just go back to using window.location to change the page and not try faking the click.

Indeed, the click() is not meant to create fake clicks but sometimes we can use it to click buttons or forms with javascript injections or just for the convenience while creating a temporary hotkey on top of existing javascript functions.

javascript - Can I call jquery click() to follow an link if I have...

javascript jquery firefox events click
Rectangle 27 81

Interesting, this is probably a "feature request" (ie bug) for jQuery. The jQuery click event only triggers the click action (called onClick event on the DOM) on the element if you bind a jQuery event to the element. You should go to jQuery mailing lists ( http://forum.jquery.com/ ) and report this. This might be the wanted behavior, but I don't think so.

I did some testing and what you said is wrong, even if you bind a function to an 'a' tag it still doesn't take you to the website specified by the href attribute. Try the following code:

<html>
<head>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
 <script>
  $(document).ready(function() {
   /* Try to dis-comment this:
   $('#a').click(function () {
    alert('jQuery.click()');
    return true;
   });
   */
  });
  function button_onClick() {
   $('#a').click();
  }
  function a_onClick() {
   alert('a_onClick');
  }
 </script>

</head>
<body>
 <input type="button" onclick="button_onClick()">
 <br>
 <a id='a' href='http://www.google.com' onClick="a_onClick()"> aaa </a>

</body>
</html>

It never goes to google.com unless you directly click on the link (with or without the commented code). Also notice that even if you bind the click event to the link it still doesn't go purple once you click the button. It only goes purple if you click the link directly.

I did some research and it seems that the .click is not suppose to work with 'a' tags because the browser does not suport "fake clicking" with javascript. I mean, you can't "click" an element with javascript. With 'a' tags you can trigger its onClick event but the link won't change colors (to the visited link color, the default is purple in most browsers). So it wouldn't make sense to make the $().click event work with 'a' tags since the act of going to the href attribute is not a part of the onClick event, but hardcoded in the browser.

I tried your code, and it does exactly as you said it does, but my code does as I described above. I'll do some more experiments and see if I can put together a simple example of my results that you can try.

Ok. It must have been something I did wrong. I was absolutely certain at the time I posted my question that it was working, but since I tried your example mine no longer works. I'll just go back to using window.location to change the page and not try faking the click.

Indeed, the click() is not meant to create fake clicks but sometimes we can use it to click buttons or forms with javascript injections or just for the convenience while creating a temporary hotkey on top of existing javascript functions.

javascript - Can I call jquery click() to follow an link if I have...

javascript jquery firefox events click