Triyugi Narayan Mani Triyugi Narayan Mani - 3 months ago 19
jQuery Question

Javascript and ctrl key conflict

There is

div
where I am using
onclick
function to redirect on some other page.

But when I am using ctrl key and mouse, the link is opening in next tab as well as in same tab. Ideally, it should open in new tab only.

Code is as follows:

<div onclick="window.location='some page url'">

Answer

Just do this :

<a href="some page url">
 <div></div>
</a>

So, when you click it's open in the same tab and when you press ctrl key, it's opening in a new tab.

EDIT : So now try this :

<div onclick="doRedirect()"></div>

<script>
    $(document).keydown(function(event){
        if(event.which=="17")
            cntrlIsPressed = true;
    });

    $(document).keyup(function(){
        cntrlIsPressed = false;
    });

    var cntrlIsPressed = false;


    function doRedirect()
    {
        if(cntrlIsPressed)
        { 
           window.open('some url','_blank');
        }
        else{
           window.location('some url');
        } 

    }
</script>

You can also specify the url in parameters.

Comments