Adding CSS Class using jQuery - javascript

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).

Related

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

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);

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";
});

Carrying Variable from external link to page and plugging into jQuery script onload

I have this jQuery which shows/hides content depending on the list item that's clicked. I also want to be able to show specific content upon landing on this page, dependant on what link the user clicked on another page.
I know that to make this happen, I have to carry the variable over from the other link somehow, and make it act as the variable.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#side_nav ul li a').click(function() {
$('#side_nav ul li.current').removeClass('current');
$(this).parent().addClass('current');
var filterVal = $(this).attr('class');
$('#content div.section').each(function() {
if($(this).hasClass(filterVal)) {
$(this).fadeIn(200);
} else {
$(this).hide();
}
});
return false;
});
});
</script>
I've tried adding #desired_content to the end of the url at the link on the separate page and I know that using window.location.hash, I can pull that hash lable in as the variable somehow but I'm lost as to exactly how to accomplish that.
Please help.
EDIT: I added this to the external page:
<li>HOW IT WORKS</li>
and this to the target page, just to TEST whether the class being added
<script type="text/javascript">
$(document).ready(function() {
var myHash = window.location.hash;
if( myHash == "#how_it_works" ){
$('#content div.how_it_works').addClass('test');
}else if( myHash == "#option2" ){
// fade in option2
}
});
</script>
I don't understand why this isn't working...
Hash URLs have mostly been used for in-page anchor tags (back to top, etc) and so I'd suggest that directing someone to a certain section of your page using hash URLs makes a lot of sense.
What I've done, once on the page, was grab the hash URL via window.location.hash and manipulate your page based on this string.
var myHash = window.location.hash;
if( myHash == "#desired_content" ){
// fade in option1
}else if( myHash == "#option2" ){
// fade in option2
}
I will suggest to store the variable on localStorage in first page then load the variable from localStorage in second page. It will be simpler rather than passing hash URL which is not the proper purpose.
First Page
Go to second page
<script type="text/javascript">
$(document).ready(function() {
$('#link').click(function(){
// set your variable when someone click the link
localStorage.setItem("myVariable", "someValue");
});
});
</script>
Second Page
<script type="text/javascript">
$(document).ready(function() {
var yourVariable = localStorage.getItem("myVariable");
// do your stuff according to this variable that passed from firstpage
//...
});
</script>

Making link to go somewhere else than its default href

I want to grab the link text and append it to the URL and open the new URL with querystring added Onclick of the Original Link..How do I get the link text using javascript or jquery?
<a href="www.mysite.com/search.aspx?kwd=" onClick="location.href='http://mysite.com/search.aspx?kwd='+ Grab text 'kangaroo' and append here as QueryString>Kangaroo</a>
You can access the current anchor through this. The text can be then had through this.innerHTML.
Something like this...
Kangaroo
$('.your-url').click(function(event) {
event.preventDefault();
window.location= $(this).attr('href') + encodeURIComponent($(this).text());
});
I noticed that none of the other answers were encoding the text in the link to be a query-string parameter.
Inline (like your example) would look like this:
Kangaroo
return false should be unnecessary because once you change the location object scripts stop running and the page changes.
UPDATE
You can use $.trim() to:
Remove the whitespace from the beginning and end of a string.
Source: http://api.jquery.com/jquery.trim/
$('a.your-url').click(function(e) {
e.preventDefault();
url = $(this).attr('href') + $(this).text();
location.href = url;
});
To send the page to the link's href + text when clicked, this should work:
$("a").click(function(){
location.href = $(this).attr("href") + $(this).text();
return false;
});
But why not just set the hrefs correctly when the page loads, and get rid of all these onclick handlers altogether?
$("a").each(function(i, el) {
var $el = $(el);
$el.attr("href", $el.attr("href") + encodeURI($el.text()));
});
jQuery example:
$('a.link').click(function () {
var $this = $(this),
href = $this.attr('href');
window.location = href + encodeURIComponent($this.text());
event.preventDefault();
return false;
});
Demo

Manage jquery click events

I'm capturing all the clicks in my "a" elements with this:
$("a").click(function(e){....});
I want to know if it's possible to discard some events depending on some variable.
For example..
If href="http://www.google.es" then alert("google.es")
else if href="http://www.google.com" then do not handle the event and let the browser do whatever it has to do.
I don't know if I've explained it very well...
Or, you could do:
$("a[href!='http://www.google.com']").click(function(e) {
e.preventDefault();
if(this.getAttribute('href') === 'http://www.google.es') alert("google.es");
});
And not generate the click event for google.com in the first place.
$("a").click(function(e){
e.preventDefault();
if (this.href == "http://www.google.es/") alert("google.es");
else if (this.href == "http://www.google.com/") window.location = this.href;
});
Fiddle Demo: http://jsfiddle.net/maniator/5XdkV/
Inside your function $(this).attr('href') should give you the href of the anchor tag - which you can then use in the rest of your logic
For your example above,
$('a[href*=.es]').click(function(e){
e.preventDefault();
});
Would make all links that contain .es in the href attribute to not be followed, but leaves the other links alone.
$("a").click(function(e) {
if ($(this).attr('href') == 'http://www.google.es') {
alert('google.es');
e.preventDefault();
}
// if code gets here, it's ok for the browser to handle normally.
}
All the suggestions posted so far will work, but they aren't the most flexible. If you want to match any link that has google.es as the hostname, I'd do something like this:
$(document.body).delegate('a', 'click', function(e) {
var hostname = this.hostname || $(this).prop('href').split('/')[1];
if (hostname == 'www.google.es') {
alert('google.es');
e.preventDefault();
}
});

Categories