I am trying to get my code to open a new tab in the browser rather than opening in the same tab, so I added target="_blank"
after the href
, but this doesn't work as I don't think it is being sent.
does anyone know how to fix this code so it works in a new window?
<script>
function changeText1(){
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "https://www.google.co.uk/search?q=" userInput ;
lnk.innerHTML = lnk.href;
window.location = "https://www.google.co.uk/search?q=" userInput;
}
function changeText2(){
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "https://www.dogpile.com/serp?q=" userInput;
lnk.innerHTML = lnk.href;
window.location = "https://www.dogpile.com/serp?q=" userInput;
}
function changeText3(){
var userInput = document.getElementById('userInput').value;
var lnk = document.getElementById('lnk');
lnk.href = "https://uk.search.yahoo.com/search?p=" userInput;
lnk.innerHTML = lnk.href;
window.location = "https://uk.search.yahoo.com/search?p=" userInput;
}
</script>
<input type='text' id='userInput' value=' ' />
<input type='button' onclick='changeText1()' value='google'/>
<input type='button' onclick='changeText2()' value='Dogpile'/>
<input type='button' onclick='changeText3()' value='Yahoo'/>
<a href="" target="_blank" id=lnk </a> <br>
I tried adding target to this bit but, it didn't work.
<a href="" target="_blank" id=lnk </a> <br>
CodePudding user response:
Maybe try adding "window.open(url, '_blank').focus();" in your function blocks.
lnk.href = "https://uk.search.yahoo.com/search?p=" userInput;
lnk.innerHTML = lnk.href;
window.open(lnk.href, '_blank').focus();
window.location = "https://uk.search.yahoo.com/search?p=" userInput;
Hard to say, try this and let me know if it works ! ??
CodePudding user response:
The a
tag does not work as you are expecting. The a
tag is used to encapsulate a link.
What would work for having the effect that you want is to refactor your functions to look like this:
function changeText1(){
var userInput = document.getElementById('userInput').value;
var url = "https://www.google.co.uk/search?q=" userInput ;
window.open(url, '_blank').focus();
}
Using the open
method of window
CodePudding user response:
You can follow the examples below: (a, button) tags
document.getElementById('btn').onclick = function () {
window.open('https://www.google.com', "_blank");
}
<a href="https://www.google.com" target="_blank">Link</a>
</br>
</br>
<button id="btn">button</button>