window.location.replace() not working to redirect browser
Your code has a syntax error. Your end parenthesis is inside the quote not outside...
Try:
<script>
$(document).ready(function() {
$("body").keydown(function(event) {
if(event.keyCode == 37) { // left
window.location.replace("http://newsii.abudayah.com/photo/2"); }
else if(event.keyCode == 39) { // right
window.location.replace("http://newsii.abudayah.com/photo/31"); }
});
});
</script>
window.location.replace is not supported in all browsers. Assigning the location value is always supported. However, the reason to use replace rather than assigning the location value is you don't want the current url to appear in the history, or to show-up when using the back button. Since this is not always possible, you just need to settle for what is possible:
<script>
$(document).ready(function() {
$("body").keydown(function(event) {
if(event.keyCode == 37) { // left
try { window.location.replace("http://newsii.abudayah.com/photo/2"); }
catch(e) { window.location = "http://newsii.abudayah.com/photo/2"; }
}
else if(event.keyCode == 39) { // right
try { window.location.replace("http://newsii.abudayah.com/photo/31"); }
catch(e) { window.location = "http://newsii.abudayah.com/photo/31"; }
}
});
});
</script>
Don't use .replace()
for this, just assign the value directly.
Example
$("body").keydown(function(event) {
if(event.keyCode == 37) { // left
window.location = "http://newsii.abudayah.com/photo/2";
}
else if(event.keyCode == 39) { // right
window.location = "http://newsii.abudayah.com/photo/31";
}
});
I was having trouble with this in Chrome. I was trying to load another page from the same domain, but was using an absolute URL (e.g.www.example.com/newurl
). I changed it to a relative URL (/newurl
) and it works now.
My thought is that this is a security feature to prevent the user from being redirected to a malicious site through some javascript ad.