I have two (or more) links. For example: http://google.com and http://yahoo.com.
How can I make them both open when I click on a single link?
For example, a link entitled "click here" which, when clicked, will open two different blank windows.
HTML:
Click Here
JS:
$('a.yourlink').click(function(e) {
e.preventDefault();
window.open('http://yoururl1.com');
window.open('http://yoururl2.com');
});
window.open also can take additional parameters. See them here: http://www.javascript-coder.com/window-popup/javascript-window-open.phtml
You should also know that window.open is sometimes blocked by popup blockers and/or ad-filters.
Addition from Paul below: This approach also places a dependency on JavaScript being enabled. Not typically a good idea, but sometimes necessary.
I did it in a simple way:
<a href="http://virtual-doctor.net" onclick="window.open('http://runningrss.com');
return true;">multiopen</a>
It'll open runningrss in a new window and virtual-doctor in same window.
You might want to arrange your HTML so that the user can still open all of the links even if JavaScript isn’t enabled. (We call this progressive enhancement.) If so, something like this might work well:
HTML
<ul class="yourlinks">
<li><a href="http://www.google.com/"></li>
<li><a href="http://www.yahoo.com/"></li>
</ul>
jQuery
$(function() { // On DOM content ready...
var urls = [];
$('.yourlinks a').each(function() {
urls.push(this.href); // Store the URLs from the links...
});
var multilink = $('Click here'); // Create a new link...
multilink.click(function() {
for (var i in urls) {
window.open(urls[i]); // ...that opens each stored link in its own window when clicked...
}
});
$('.yourlinks').replaceWith(multilink); // ...and replace the original HTML links with the new link.
});
This code assumes you’ll only want to use one “multilink” like this per page. (I’ve also not tested it, so it’s probably riddled with errors.)
You can open multiple windows on single click... Try this..
<a href="http://--"
onclick=" window.open('http://--','','width=700,height=700');
window.open('http://--','','width=700,height=500'); ..// add more"
>Click Here</a>`
You need to unblock the pop up windows for your browser and the code could work.
chrome://settings/contentExceptions#popups
I created a bit of a hybrid approach between Paul & Adam's approach:
The link that opens the array of links is already in the html. The jquery just creates the array of links and opens each one when the "open-all" button is clicked:
HTML:
<ul class="links">
<li></li>
<li></li>
</ul>
<a id="open-all" href="#">OPEN ALL</a>
JQUERY:
$(function() { // On DOM content ready...
var hrefs = [];
$('.links a').each(function() {
hrefs.push(this.href); // Store the URLs from the links...
});
$('#open-all').click(function() {
for (var i in hrefs) {
window.open(hrefs[i]); // ...that opens each stored link in its own window when clicked...
}
});
});
You can check it out here:
https://jsfiddle.net/daveaseeman/vonob51n/1/
Here is a basic implementation in javascript - I separated it into an external file
HTML
Click To Open Links
JS
var myLinks = [
"https://google.com",
"https://www.w3schools.com/jsref/met_win_open.asp",
"https://developer.mozilla.org/en-US/docs/Web/API/Window/open"
]
function openMultipleLinks(links) {
for (var i = 0; i < links.length; i ++) {
window.open(links[i]);
}
}
Note that the user will have to enable pop-ups for the pages to open.
Here it is in action: https://jsfiddle.net/cuppajoeman/rjavuhcg/
If you prefer to inform the visitor which links will be opened, you can use a JS function reading links from an html element. You can even let the visitor write/modify the links as seen below:
<script type="text/javascript">
function open_all_links() {
var x = document.getElementById('my_urls').value.split('\n');
for (var i = 0; i < x.length; i++)
if (x[i].indexOf('.') > 0)
if (x[i].indexOf('://') < 0)
window.open('http://' + x[i]);
else
window.open(x[i]);
}
</script>
<form method="post" name="input" action="">
<textarea id="my_urls" rows="4" placeholder="enter links in each row..."></textarea>
<input value="open all now" type="button" onclick="open_all_links();">
</form>
Related
Take a look at the following JavaScript for me that opens a pop up window, please:
function openPopup(e) {
e.preventDefault();
window.open(this.href, "popupWindow", "width=600,height=600,scrollbars=yes");
}
var el = document.querySelector(".bbc-popup");
el.addEventListener("click", openPopup);
Here is a JSFiddle of it in action:
http://jsfiddle.net/dvadcgps/1/
However, when I include it on my page, the code doesn't work, and the link opens in the current tab. The only external JavaScript resources I rely on are jQuery (1.11.3) and Bootstrap 3, and those are both included within the above fiddle, to no effect.
What other reasons could there be for this code to not work?
Here is the full HTML code of the page, with all external resources included, for you to see how it stops working... the links that should open popups are behind the View Chairs' Builds button:
http://jsfiddle.net/e60y004n/1/
Working off Brian Ray's comment, I had to ensure the Event Listener was added to every element, as my current code was only adding it to the first.
Firstly, I add all the elements I want to be targeted to an array.
var chairPopup = document.getElementsByClassName("chair-popup");
I then loop through every element in that array, adding the Event Listener to each:
for (var i = 0; i < chairPopup.length; i++) {
chairPopup[i].addEventListener("click", openPopup);
}
The full code, with the function(), reads as follows:
var chairPopup = document.getElementsByClassName("chair-popup");
function openPopup(e) {
e.preventDefault();
window.open(this.href, "popupWindow", "width=300,height=1000,scrollbars=yes");
}
for (var i = 0; i < chairPopup.length; i++) {
chairPopup[i].addEventListener("click", openPopup);
}
In an answer that has since been deleted by it's author, they mentioned a need to change popupWindow to _blank within the window.open() function. I can confirm that this is needed, otherwise each link opens up in the same popup window.
window.open(this.href, "_blank", "width=300,height=1000,scrollbars=yes");
I'm trying to use javascript to iterate over an array of "magnet:.." links and download them iteratively.
I am using an iframe to download the link this way:
the HTML code:
<button ng-click="downloadSelected()">Get All Selected</button>
.
.
<iframe id='downloader_iframe'></iframe>
Inside the controller:
function downloadSelected(){
for (var i=0; i<$scope.magnets.length; i++){
document.getElementById('downloader_iframe').src = $scope.magnets[i];
}
}
The problem is that the action is happening only for the first link in the array while the rest of them ignored completely.
Is there any way to do it?
Make use of window.open or .click on an <a>, for example
function downloadSelected() {
var i;
for (i = 0; i < $scope.magnets.length; ++i) {
window.open($scope.magnets[i], '_blank');
}
}
I came here but actually found this solution/answer more helpful.
Creating a hidden iframe:
<iframe style="display:none" name="magnetframe"></iframe>
window.open(magnet_uri, 'magnetframe')
Im not sure how this would work with multiple magnet links, maybe if you use multiple iframes? (use 4 iframes and reload another magnet link every 0.5 second per frame so you can process 8 magnet links per second?)
another solution by using chrome API.
chrome.tabs.update({url: magnet_uri});
if you want to running at new tab, then add tab id in arguments
chrome.tabs.create({active: false}, function(tab) {
chrome.tabs.update(tab.id, {url: magnet_uri});
});
Let's say I have a single HTML page and it contains hundreds of links. These links will load in the same window when anybody clicks them.
I want it to open in another window. I know that I can use target for each link:
My Text1
My Text2
My Text3
Howeder, I'd prefer to use JavaScript if that's possible. Is it possible to do that with JavaScript, and if so, how?
Yes, it is. Use something like this:
var newtab = window.open('http://www.example1.com/', '_blank');
newtab.focus();
This may open in new tabs or new windows depending on the particular browser, but I don't know of a way to control that any more specifically.
EDIT
Or were you asking for a way to set the behavior for all links on the page? Then you can add the proper target to all of them when the page loads.
With jQuery: http://jsfiddle.net/b8hdv/
$(document).ready(function() {
$('a').attr('target', '_blank');
});
...or without jQuery: http://jsfiddle.net/uFvUS/
window.onload = function(e) {
var links = document.getElementsByTagName('a');
for (var i = 0; i < links.length; i++) {
links[i].target = '_blank';
}
}
function open_in_new_tab(url )
{
var win=window.open(url, '_blank');
win.focus();
}
Use like this:
$("#a_id").on("click", function(){
open_in_new_tab($(this).attr("href"));
});
Demo HTML:
Click me!
Found here
Try this:
window.open('http://www.example1.com');
and capture the event click.
I have a question that will be found very often. The problem is that nowhere can be found an explicit solution.
I have two problems regarding anchors.
The main goal should be to get a nice clean url without any hashes in it while using anchors to jump on a page.
So the structure of the anchors is:
<ul>
<li>One</li>
<li>Two</li>
<li>Three</li>
</ul>
<div class="wrap">
<a name="one">text 1</a>
<a name="two">text 2</a>
<a name="three" class="box">text 3</a>
</div>
Okay, if you will click one of the links the url will automatically change to
www.domain.com/page#1
At the end this should be just:
www.domain.com/page
So far, so good. Now the second thing is, when you search the internet for that problem you will find javascript as a solution.
I have found this function:
function jumpto(anchor){
window.location.href = "#"+anchor;
}
and calling that function with:
<a onclick="jumpto('one');">One</a>
what will be the same like before. It will add the hash to the url. I also added
<a onclick="jumpto('one'); return false;">
without success. So if there is someone who could tell me how to solve this I really would appreciate.
Thanks a lot.
You can get the coordinate of the target element and set the scroll position to it. But this is so complicated.
Here is a lazier way to do that:
function jump(h){
var url = location.href; //Save down the URL without hash.
location.href = "#"+h; //Go to the target element.
history.replaceState(null,null,url); //Don't like hashes. Changing it back.
}
This uses replaceState to manipulate the url. If you also want support for IE, then you will have to do it the complicated way:
function jump(h){
var top = document.getElementById(h).offsetTop; //Getting Y of target element
window.scrollTo(0, top); //Go there directly or some transition
}
Demo: http://jsfiddle.net/DerekL/rEpPA/
Another one w/ transition: http://jsfiddle.net/DerekL/x3edvp4t/
You can also use .scrollIntoView:
document.getElementById(h).scrollIntoView(); //Even IE6 supports this
(Well I lied. It's not complicated at all.)
I think it is much more simple solution:
window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"
This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.
I don't have enough rep for a comment.
The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).
Something to bear in mind if you don't have control of the document markup (e.g. webextension).
The location based method in the selected answer can also be simplified with location.replace:
function jump(hash) { location.replace("#" + hash) }
Because when you do
window.location.href = "#"+anchor;
You load a new page, you can do:
One
<script>
function getPosition(element){
var e = document.getElementById(element);
var left = 0;
var top = 0;
do{
left += e.offsetLeft;
top += e.offsetTop;
}while(e = e.offsetParent);
return [left, top];
}
function jumpTo(id){
window.scrollTo(getPosition(id));
}
</script>
I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.
On the .html file I have:
<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>
On the .js file I have
function myFunction() {
var input = prompt("list or new or quit");
while(input !== "quit") {
if(input ==="test100") {
window.location.hash = 'test100';
return;
// else if(input.indexOf("test100") >= 0) {
// window.location.hash = 'test100';
// return;
// }
}
}
}
When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.
I use Google Chrome.
Note: This idea comes from linking on the same page using
Test link
which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.
Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ☺
The first suggested solution of accepted solution did not work for me entirely. The main problem was when it was already jumped to hash, and hash already in url, jump did not happen again. I propose here, for the sake of completeness, somewhat more elaborate solution which works (tested in Chrome and FF). el is element with anchor tag.
el.addEventListener('click', function(ev) {
ev.preventDefault();
const href = ev.target.getAttribute('href');
const hashIndex = href.indexOf('#');
if (hashIndex !== -1) {
const hashPart = href.substring(hashIndex);
if (location.hash === hashPart) {
document.querySelector(hashPart).scrollIntoView();
}
else {
location.hash = hashPart;
}
}
})
I have a div that is represented in multiple pages across my site. I don't want to set each one specifically to open in a new window, rather I want all links in that specific div to open in a new window. How can I do this using HTML/ CSS/ javascript?
Thanks
here's how you could do that with jQuery
if you have something like <div class="myLinks">...</div>
$('.myLinks a').attr("target", "_blank");
Well, I guess there are two reasonable ways to open the href from an anchor in a new window.
Edit the node and set its target to _blank ()
Use Javascript to catch the click event, prevent the default behavior and call window.open()
var anchors = document.querySelectorAll('#mydiv a');
[].forEach.call(anchors, function(anchor) {
anchor.addEventListener('click', function(e) {
window.open(e.target.href, 'mywindow', '_blank');
e.preventDefault();
e.stopPropagation();
}, false);
});
That example code is vanilla Javascript and it'll only work in a W3C compliant browser (!= IE).
If you can afford to you use a JS framework live is going to be easier since all of those will abstract browser differences for you.
I think you have a div and link like this in some pages:
<div id="myDiv">
Link Text
<!--some other elements-->
</div>
you need to create a js file like bellow and add it to end of all of your pages :
var div = document.getElementById("myDiv");
if (div) {
for (var i = 0; i < div.childNodes.length; i++)
{
if (div.childNodes[i].nodeName.toLowerCase() == "a")
div.childNodes[i].target = "_blank";
}
}
And its all things you need to do !
this code is fast enough and even does not need JQuery.
Couldn't you use jQuery to iterate through all links within a specified div, then set the target to "_blank".
You can use javascript and jQuery.
First of all I suggest that DIV have id outgoing.
<div id='outgoing'>
<a href='http://google.com'>Go to Google</a><br>
<a href='http://stackoverflow.com'>Look at SO!</a>
</div>
Now we can use simple JavaScript to dynamiclaly add target='blank' into these links:
$(function() {
$('#outgoing a').attr('target', '_blank');
});
You can check example here