How to automatically add rel="noopener" to a target="_blank" link? - javascript

I have a little JS that include target="_blank" to all external link. For security reasons I need to append also rel="noopener".
Any help to achieve this goal?
My script:
(function($) {
jQuery(document).ready(function() {
add_target_blank_to_external_links();
});
function add_target_blank_to_external_links() {
$('a[href^="http://"], a[href^="https://"]').not('a[href*="' + location.hostname + '"]').attr('target', '_blank');
}
})(jQuery);

So, your final solution is like below.
N.B. It's very good practice to use rel="noopener" because it prevents the new page from reaching back to control the initial page. you can also use like rel="noreferrer"
(function($) {
jQuery(document).ready(function() {
add_target_blank_to_external_links();
});
function add_target_blank_to_external_links() {
$('a[href^="http"]').not('a[href*="' + location.hostname + '"]').attr({target: "_blank", rel: "noopener"});
}
})(jQuery);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Demo link

One small improvement to labu4bd's answer above (very useful, thank you!) is to change the initial filter to only amend links in the body so they are not added to style & script links in the head.
For example:
(function($) {
jQuery(document).ready(function() {
add_target_blank_to_external_links();
});
function add_target_blank_to_external_links() {
$('body a[href^="http"]').not('a[href*="' + location.hostname + '"]').attr({target: "_blank", rel: "noopener"});
}
})(jQuery);

Related

Add anchor to links using jquery

I'm new to javascript.
Need to remove any existing anchors (eg: #page33) add other anchor (eg: #page1) to all links in a list dynamically (client side) with javascript or jquery:
Initial html (from server):
<ul id="lang_menu">
<li>English</li>
<li>Tamil</li>
<li>Sinhala</li>
</ul>
this should behave like (replace #page33 with #page1 at client side):
<ul id="lang_menu">
<li>English</li>
<li>Tamil</li>
<li>Sinhala</li>
</ul>
This is where I need this Developing Website
Please help me. Thanks in advance...
Try this way:-
$(function () {
$('#lang_menu li a').attr('href', function (_, oldHref) {
return oldHref + "#page1";
});
});
Demo
For your updated question you can try something like this:
using regex to replace the #part from the url.
$(function () {
$('#lang_menu li a').attr('href', function (_, oldHref) {
oldHref = oldHref.replace(/\#(.*)/g, "#page1");
if(oldHref.indexOf('#') == -1)
oldHref += "#page1";
return oldHref;
});
});
Demo2
If you are dealing with a lot of DOM elements its less expensive to add the anchor lazily.
jQuery("a").bind("click", function(e) {
e.preventDefault();
document.location = jQuery(this).attr("href") + "#page1";
});

JQuery with Element ID

I am trying to create a bit of jquery code to update an element but im having a problem. It wont update and I think its because of the element id?
Here is my JS Code:
<script type="text/javascript">
$(document).ready(function()
{
$("#vote_button_" + $(this).attr('id')).click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});
</script>
And this is the HTML Code:
<div class="vote_container">
<div class="vote_button" id="vote_button_31"><img src="/images/picture_31.png"></div>
<div class="vote_count" id="vote_count">0</div>
</div>
You're telling it to use the ID of the document (I think).
You can surely just do:
$("#vote_button_31").click(function()
{
$("#vote_count").show().html('<h2>voting, please wait...</h2>');
});
If you want the code to work on all vote buttons try this:
$(".vote_button").click(function()
{
$(this).siblings('.vote_count').show().html('<h2>voting, please wait...</h2>');
});
$("#vote_button_" + $(this).attr('id')).click(function()...
The way you've called it, this has no context at all. Since you have a class on the div in question, why not use that instead?
$(".vote_button").click(function() {...
That will also work if you don't know the id in question when the page is loaded. If you're dynamically adding the divs then you might want to use live or delegate:
$(".vote_button").live("click", function() {...
Why you don't select the element directly:
<script type="text/javascript">
$(document).ready(function()
{
$("div#vote_button_31").click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});
</script>
YOu cannot do this. Instead try this:
<script type="text/javascript">
$(document).ready(function()
{
$(".vote_button").click(function()
{
$("div#vote_count").show().html('<h2>voting, please wait...</h2>');
});
});

Javascript , jQuery - what have I done wrong?

$(document).ready(function () {
$("href").attr('href', 'title');
});
$('a[href$=.jpg]').each(function () {
var imageSrc = $(this).attr('href');
var img = $('<img />').attr('src', imageSrc).css('max-width', '300px').css('max-height', '200px').css('marginBottom', '10px').css('marginTop', '10px').attr('rel', 'lightbox');
$(this).replaceWith(img);
});
});
This is the jQuery code I have at the moment, which I want to change all links' href to the same as their title, before then embedding them in the page. Yet with the changing href to title bit in the code, it stops working. I'm new to Javascript so am definitely doing something wrong, just not sure what yet! Any help much appreciated!
Thank you guys
EDIT
This is the html that I want to change:
<p class="entry-content">Some interesting contenthttp://example.com/index.php/attachment/11</p>
You are changing it wrong, you are trying to select href elements instead of a.
This fix should do it:
$("a[title]").each(function() {
$(this).attr('href',$(this).attr('title'));
});
It will select all a elements with title and set the href with this value.
Here's a much more efficient way.
Since you're just replacing the <a> elements, there's really no need to change its href. Just select the <a> elements that end with jpg/jpeg, and use that attribute directly.
Example: http://jsfiddle.net/5ZBVf/4/
$(document).ready(function() {
$("a[title$=.jpg],[title$=.jpeg]").replaceWith(function() {
return $('<img />', {src:this.title, rel:'lightbox'})
.css({maxWidth: 300,maxHeight: 200,marginBottom: 10,marginTop: 10});
});
});​
Your .each() is outside the .ready() function.
You can accomplish the href change easily like this:
$(document).ready(function () {
$("a").attr('href', function() { return this.title; });
});
The .attr() method will accept a function where the return value is the new value of (in this case) href.
So the whole thing could look like this:
Example: http://jsfiddle.net/5ZBVf/3/
$(document).ready(function() {
$("a[title]").attr('href', function() { return this.title; })
.filter('[href$=.jpg],[href$=.jpeg]')
.replaceWith(function() {
return $('<img />', {src:this.href, rel:'lightbox'})
.css({maxWidth: 300,maxHeight: 200,marginBottom: 10,marginTop: 10});
});
});
This line:
$("href").attr('href','title');
Is finding all href elements and replacing their href attr with the string 'title'. Since there is no such thing as an href element, Try this instead:
// for every anchor element on the page, replace it's href attribute with it's title attribute
$('a').each(function() {
$(this).attr('href', $(this).attr('title');
});
Check this out: http://jsfiddle.net/TbMzD/ Seems to do what you want.
Note: $(document).ready() is commented because of jsfiddle, you actually need it in your code.
Try:
$("a").each(function () {
var $this = $(this);
$this.attr('href', $this.attr('title'));
});

Adding CSS Class using jQuery

Below I have included the jquery code I am using to add a css class to the link in the side column that equals the active url, but it's not working, and at some point it did.
Link: http://www.liquidcomma.com/portfolio/project/TSF_Robot_Ad/1/
<script type="text/javascript">
$(document).ready(function(){
$("ul.right_submenu > li > a").each(function() {
if ($(this).attr("href") == location.href)
{
$(this).addClass("CurrentProject");
});
};
</script>
Well, besides that code missing braces and parens it can be done much simpler:
$(function(){
$("a[href^='" + location.href + "']").addClass("CurrentProject");
});
You have unclosed braces in your script:
$(document).ready(function(){
$("ul.right_submenu > li > a").each(function() {
var a = $(this);
if (a.attr('href') == location.href) {
a.addClass("CurrentProject");
}
});
});
and you could rewrite your script like this:
$('ul.right_submenu > li > a[href=' + location.href + ']')
.addClass('CurrentProject');
Following your link, my location.href goes to http://www.liquidcomma.com/portfolio/project/TSF_Robot_Ad/1/ but your project link in the page points to http://www.liquidcomma.com/portfolio/project/trade_show_fabrications/1... that will make attr('href') != location.href.
In the other links, location.href will be ending with a slash whereas the link's href will not.
You should use something else to match your project other than the href attribute, if you expect it to change in the future (and it probably will).

Noobie Jquery Question - Why doesn't this simple script work?

I'm learning JQuery and I wrote a simple AJAX external script for my homepage that tries to load some static markup from a seperate html file and insert it into my homepage when i hover over a link...
$(function()
{
$('a#contact_link').hover(function()
{
alert('test1');
$('<div id="contact_container">').load('contact.htm #contact', function()
{
alert('test2');
/*$(this) + '</div>';
$(this).hide()
.insertAfter('#header')
.slideDown(1000) */
});
return false;
});
});
at this point, i'm simply trying to get the 'test2' alert box to show, which is why i have the code below that commented out. currently, the 'test1' alert box is the only the one that shows, meaning the 'test2' alert line never gets hit. your thoughts?
here's the snippet of code from my contact.htm file...
<div id="contact_container">
<div id="contact">
<p>
<strong>NAME</strong>: My Name<br/>
<strong>EMAIL</strong>: My Email<br/>
<strong>SKYPE</strong>: My Skype Handle<br/>
<strong>ADDRESS</strong>: My Address<br/>
</p>
</div><!--end contact-->
</div><!--end contact_container-->
thanks so much in advance for your help!
You were calling $.load using incorrect selector syntax, a selector is not an HTML string, it must conform to the syntax rules set by the jQuery Selectors manual:
$('a#contact_link').hover(function()
{
alert('test1');
$('div#contact_container').load('contact.htm #contact', function()
{
alert('test2');
/*$(this) + '</div>';
$(this).hide()
.insertAfter('#header')
.slideDown(1000) */
});
return false;
});
The selector is probably the cause.
$(function()
{
$('a#contact_link').hover(function()
{
alert('test1');
$('#contact_container').load('contact.htm', function()
{
alert('test2');
/*$(this) + '</div>';
$(this).hide()
.insertAfter('#header')
.slideDown(1000) */
});
return false;
});
});
I believe your #contact_container selector is not quite kosher. Check out the selector doco (http://docs.jquery.com/Selectors) at the JQuery site. I think something like this might be a little better:
$(function()
{
$('a#contact_link').hover(function()
{
alert('test1');
$('#contact_container').load('contact.htm #contact', function()
{
alert('test2');
/*$(this) + '</div>';
$(this).hide()
.insertAfter('#header')
.slideDown(1000) */
});
return false;
});
});

Categories