Use HTML/CSS/Javascript to open links in new pages - javascript

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

Related

Open links in another window with javascript

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.

How to make a link open multiple pages when clicked

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>

How do I use colorbox to show hidden divs on my page without hardcoding?

I'm using Colorbox to show the html content of hidden divs on my page. I can get this to work perfectly with the following:
$("a.colorbox").colorbox({width:"600px", inline:true, href:"#344"});
This will show the div with the ID of 344.
However, because I'm trying to build a scalable and dynamic page with WordPress, I want to be able to grab the ID of my divs through a function, rather than hard code them in the jquery call.
I modified Jack Moore's example:
$("a[rel='example']").colorbox({title: function(){
var url = $(this).attr('href');
return 'Open In New Window';
}});
so that it looks like this:
$(".colorbox").colorbox({width:"600px", inline:true, href:function(){
var elementID = $(this).attr('id');
return elementID;
}});
The problem with this is that the href property of the colorbox function is looking for a string with a # mark infront of the ID. I tried various ways of concatenating the # to the front of the function, including the # in the return value, and concatenating the # to the elementID variable. No luck.
I also tried using the syntax in Jack's example (with no luck) so that my return statement looked like this:
return "#'+elementID+'";
I think my basic question is: How do I use colorbox to show hidden divs on my page without hardcoding everything?
Thanks for your help,
Jiert
I didn't really like any of the answers given above. This is how I did it (similar but not quite the same).
I also fully commented it for people a bit new to Javascript and the colorbox plug in.
$(document).ready(function() { //waits until the DOM has finished loading
if ($('a.lightboxTrigger').length){ //checks to see if there is a lightbox trigger on the page
$('a.lightboxTrigger').each(function(){ //for every lightbox trigger on the page...
var url = $(this).attr("href"); // sets the link url as the target div of the lightbox
$(url).hide(); //hides the lightbox content div
$(this).colorbox({
inline:true, // so it knows that it's looking for an internal href
href:url, // tells it which content to show
width:"70%",
onOpen:function(){ //triggers a callback when the lightbox opens
$(url).show(); //when the lightbox opens, show the content div
},
onCleanup:function(){
$(url).hide(); //hides the content div when the lightbox closes
}
}).attr("href","javascript:void(0)"); //swaps the href out with a javascript:void(0) after it's saved the href to the url variable to stop the browser doing anything with the link other than launching the lightbox when clicked
//you could also use "return false" for the same effect but I proffered that way
})
}
});
And this is the html:
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
I think it would work with multiple lightboxes on the one page but I haven't tested it with that.
I'm facing the same issue. What does your html look like? meaning, how did you structure your "divs"
Mine looks like this:
Javascript:
<script>
$(document).ready(function () {
$("a.colorbox").colorbox({ width: "50%", inline: true, href: function () {
var elementID = $(this).attr('id');
return "#" + elementID;
}
});
});
</script>
And the html looks like (I tried changing the display:none):
<a class='colorbox' href="#">Inline HTML</a>
<div style="display:none">
<div id="pop">
This data is to be displayed in colorbox
</div>
</div>
return "#" + elementID;
will have the desired effect as David says.
This is the way I got it to work
HTML: (taken from the example in one of the answers)
<a class="lightboxTrigger" href="#lightboxContent">Lightbox trigger</a>
<div id="lightboxContent" class="lightboxContent"> <!-- the class is just to make it easier to style with css if you have multiple lightboxes on the same page -->
<p>Lightbox content goes here</p>
</div>
Javascript:
$('a.lightboxTrigger').click(function(){
var ref = $(this).attr("href");
$.colorbox({ html: $(ref).html() });
$.colorbox.resize();
});

goto HTML document location dynamically

My page adds # to the html programatically and have this in the tag
function InsertTag(){
//Add <a name="spot"></a> to the middle of this document
}
window.addEventListener('load', InsertTag, false);
my question is how can I make the document then jump to #spot?
Here's a suggestion: use id's instead. If you have:
<div id="something">
Then page.html#something will take you straight to that div. It doesn't have to be a div, it can be used on any element. If you can manipulate the DOM to add that anchor, I am pretty sure you'll be able to do this.
Now... To get there, you can use:
// this approach should work with anchors too
window.location.hash = 'something';
// or scroll silently to position
var node = document.getElementById('something');
window.scroll(0, node.offsetTop);
See it in action here: http://ablazex.com/demos/jump.html
There are subtle differences between the methods. Eg: The first one will cause the location on the address bar to be updated, the second one won't.
If you want it to look nicer you can use a jQuery plugin, like ScrollTo.
Try
window.location = currentUrl+'#spot';
where currentUrl is a variable having the address of the current url
You can try this.
var el = document.getElementById('spot');
var eloffsetTop = el.offsetTop;
window.scroll(0,eloffsetTop);

Change link targets

Is there a way (I assume it would be with javascript) that I can have a checkbox or link on my page that will make all the links on my page have target="_blank"?
I want to have a checkbox that says something like "Open all links in new page/tab" on my site that when checked will change the target and unchecked will put it back to how it was.
jQuery example
$(function() {
$('#yourCheckoxId').toggle(function() {
$('a').attr('target', '_blank');
},
function() {
$('a').removeAttr('target');
});
});
You might want to try jQuery as an alternative to genuine Javascript
the actual code could look something like that:
$('a').attr(target, '_blank')
Modifying the target attribute of all the anchors on the page is merely a matter of getting all links, and setting their target properties one by one:
var anchors = document.getElementsByTagName("a");
for(var i = 0; i < anchors.length; i++) {
anchors[i].target = '_blank';
}

Categories