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.
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;
}
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With