How to open a link in a new window without calling onclick
I have HTML code as follows:
<a href="#" onclick="reloadPage()">Text</a>
When the user clicks the "Left mouse button" on the link, then reloadPage () is called.
But when the user presses the "Ctrl + click" or "middle button" button in the link, I want to open a new window without reloadPage ().
How can i do this?
You can refference here . His code
<a href="#" id="test" onclick="reloadPage(event)">Click Me</a>
<script>
$(document).ready(function() {
$(document).keydown(function(event){
if(event.which==17)
cntrlIsPressed = true;
});
$(document).keyup(function(){
cntrlIsPressed = false;
});
});
var cntrlIsPressed = false;
function reloadPage(mouseButton,event)
{
//event.preventDefault();
if( event.which == 2 ) {
//todo something
//window.open($("#test").attr("href"));
alert("middle button");
return false;
}
if(cntrlIsPressed)
{
//window.open($("#test").attr("href"));
// ctrl + click
return false;
}
//todo something
window.location.href = $("#test").attr("href");
return true;
}
</script>
You can try this approach (html):
<a href="#" id="mylink">Text</a>
JavaScript:
$(function () {
$("#mylink").click(function (event) {
if ((event.button == 0 && event.ctrlKey) || event.button == 1) {
event.preventDefault();
window.open("http://www.google.com");
}
else
if (event.button == 0)
window.location.reload();
});
});
I have two options for you.Pure javascript and using jquery.
Here is the full code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#jqueryStyle').mousedown(function(e){
//3 is right click
if(e.which == 3){
window.open("http://www.w3schools.com");
//1 is for click
}else if(e.which == 1){
reloadPage();
}
});
});
function reloadPage(){
location.reload();
}
function onMouseDown(e,obj){
e = e || window.event;
//3 is for right click
if(e.which == 3){
window.open("http://www.w3schools.com");
//1 is for click
}else if(e.which == 1){
reloadPage();
}
}
</script>
</head>
<body>
<a href="#" id="jqueryStyle">JQuery Code</a ><br/>
<a href="#" onmousedown="onMouseDown(event,this)">Pure Javascript Code</a >
</body>
</html>
Hope this helps.