Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulating a click on a link in Javascript/jQuery that yields normal browser behavior

Right 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 div, the Javascript will simulate a click on the actual link and take you to the destination page.

However, this doesn't work quite so well when you try to ctrl-click, as the browser won't open a new tab, and instead just loads the url into the current window.

Instead of this behavior, I want to have normal browser behavior (i.e. open a new tab, don't change the current window for a ctrl-click) when the background is clicked. Is there a way to do this in Javascript/jQuery?

I'd prefer not to try to detect the "ctrl" key being depressed—there are a few similar cases and I'd rather have a solution that solves everything rather than try to catch every edge case like this.

like image 864
waiwai933 Avatar asked Jan 05 '13 07:01

waiwai933


2 Answers

A function that will do this (either new window or tab, can't control which)...

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

Of course, you will have to capture the Ctrl keypress...

$(window).keypress(function(event) {
    if (event.ctrlKey) {
        // set flag
        flag = true;
    } else {
        // unset flag
        flag = false;
    }
});
like image 152
Ian Atkin Avatar answered Oct 04 '22 05:10

Ian Atkin


I know this isn't javascript but I think that a good solution would be to use an absolutely positioned link and setting its z-index to a negative number so that clicking on the content in the div will not go to the link. (unless this isn't desired than just ignore the z-index) Then clicking on the background of the div will act like a regular link. See this fiddle

Here is the HTML

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

And the 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 with css if you don't want it to look like the div is a link.

like image 27
Blake Plumb Avatar answered Oct 04 '22 06:10

Blake Plumb