Simulating a click on a link in Javascript / jQuery, which gives normal browser behavior

Now I have the following code:

<script> $("#clickme").click(function(){ $("#clicker").click(); }); </script> <div id="clickme" style="height:20em; width:20em;"> <a id="clicker" href="http://www.google.com"> Link </a> </div> 

Effectively, if you click anywhere on the background of the div, Javascript will simulate a click on the actual link and lead you to the landing page.

However, this does not work so well when you try ctrl-click, since the browser will not open a new tab and instead simply loads the url into the current window.

Instead of this behavior, I want to have the usual browser behavior (i.e. open a new tab, do not change the current window for clicking Ctrl) when clicking on the background. Is there a way to do this in Javascript / jQuery?

I would rather not try to detect the "ctrl" key press - there are several similar cases, and I would rather have a solution that solves everything, and not try to catch every edge case like this.

+6
source share
2 answers

The function that will do this (a new window or tab cannot control which one) ...

 function open_url(url ) { if (flag) { window.open(url, '_blank'); window.focus(); } else { window.location.href = url; } } 

Of course, you will need to capture the Ctrl key ...

 $(window).keypress(function(event) { if (event.ctrlKey) { // set flag flag = true; } else { // unset flag flag = false; } }); 
+2
source

I know this is not javascript, but I think a good solution would be to use an absolutely positioned link and set its z-index to a negative number, so clicking on the content in the div will not be a link. (if this is not desired, just ignore the z-index). Then clicking on the background div will act like a regular link. See fiddle

Here is the HTML

 <div id="clickme"><a id="clicker" href="http://suu.edu"></a><p>text text</p></div> 

And CSS

 #clickme{ position: relative; width: 500px; height: 500px; border: 1px solid #000; z-index: 1; } #clicker{ position: absolute; width: 100%; height: 100%; z-index: -1; } 

You can change the cursor to css if you don't want it to look like a div - this is a link.

+2
source

All Articles