jQuery Make a Link in Active Status - javascript

I am working on a HTML template, but I cannot touch the HTML code, I can only work on CSS and JS files. So I cannot in any way edit the HTML code.
What I am trying to achieve is to put some links in active status when jQuery or Javascript recognizes that the current page URL is the same one of the link I want to put in active status, without editing the HTML code.
Is there a way to do it? I tried in many ways but with no luck.
Here is the HTML code ( Remember I cannot edit it ).
<span class="Tag_Nav_Aux">
Create Account
|
Login
|
My Cart
</span>
The jQuery or Javascript code should work on different links, other than the ones I reported above, since the HTML changes when the user is logged in or logged out.
So the jQuery should point the class Tag_Nav_Aux and add the Active class to any a tag it will find that has the link the same of the current URL.

You can do something like this. Your file name from the URL
var filename = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
After that get the anchor from the navigation and apply some class.
$("span.Tag_Nav_Aux a[href*="+filename+"]").addClass('active');
Here you have to write a CSS active class which will make that link to appear like an active link.

Try this script
jQuery(function($){
$('.Tag_Nav_Aux a').filter(function(){
return $(this).attr('href').toLowerCase() === window.location.pathname.toLowerCase();
}).addClass('active');
});
and create a CSS rule for
.Tag_Nav_Aux a.active{
// style you want the active link to have
}

$(document).ready(function() {
var url = window.location.href.toLowerCase();
$(".Tag_Nav_Aux a").each(function() {
var $this = $(this);
var href = $this.attr("href").toLowerCase();
if(url.indexOf(href) > -1) {
$this.addClass("active");
}
});
});​

I think you need to check the current page url and assign a class to the item like to active.
I usually do putting class="active" based on current URL match with help of server side code.
But if you dont want server code you can do with help of JavaScript
var currentPage=window.location.href;
if(currentPage=="")
{
//logic to find and add a Class for the proper anchor tag
}

Related

Remove "#comments" from dynamically loaded URLs?

I've got a problem where all the dynamic links on my homepage have "#comments" at the end, making it so when the user clicks their screen is annoyingly jolted down to the 'Comments' section each time rather than staying on top.
Example URL:
https://example.com/441447279/amazing-art/#comments
Is there a way to dynamically strip them of the 'comments' part via jQUery?
They're always the SECOND link in a unique class <p class="g1-meta entry-meta entry-byline entry-byline-s entry-byline-with-avatar">
so I was thinking something like
var linkURL = $(".g1-meta.entry-meta.entry-byline.entry-byline-s.entry-byline-with-avatar").find("a").prop('href');
but I don't know how to make it retrieve the SECOND link instead of the 1st.
And I don't know where to go from there... Help appreciated.
Use this
//The key here is to use nth-of-type selector
$(".g1-meta.entry-meta.entry-byline.entry-byline-s.entry-byline-with-avatar").find("a:nth-of-type(2)").each(function(){
let link = $(this).prop('href').replace('#comments','');
$(this).prop('href',link)
})
Or without jQuery
Array.from(document.querySelectorAll('.g1-meta.entry-meta.entry-byline.entry-byline-with-avatar')).forEach(function(node){
let anchorNode = node.querySelectorAll('a')[1];
anchorNode.href= anchorNode.href.replace('#comments','');
})

How to check if link is present on a page with Jquery?

I have this link on my web page:
Terms and conditions
I want to use Jquery to check whether this specific link is present or not on the web page. I know how to check if text is present on a page, but am struggling a little with links. If it helps, it is only the terms-conditions-mywebsite bit that I need to use (as mywebsite changes depending on who is using the site).
The class is footer so I have tried $('.footer:contains("terms-conditions") but this doesn't seem to work. Any pointers would be appreciated, thanks so much :)
Edit: I need to check that the actual specific contents of this links is present, rather than the text 'Terms and conditions'
You should check the value of href attribute. You can use Attribute Contains Selector [name*=”value”] which select elements that have the specified attribute with a value containing a given substring:
The following should work:
if($('a[href*=terms-conditions]').length){
//exist
}
OR: Check the link string directly
if($('a:contains("Terms and conditions")').length){
//exist
}
I would look at doing this with Javascript, as it's very straightforward and means you are not reliant on JQuery should you wish to remove JQuery from the site at a later date.
// get <a> elements
var links = document.getElementsByTagName('a');
// loop through each <a>
for (var i = 0; i < links.length; i++) {
// get each href
var hrefs = links[i].getAttribute("href");
// check href against the one you want
if (hrefs == "https://www.google.com") {
// check content of link
console.log('link content:', links[i].innerHTML)
}
}

Jquery script not working to alter CSS on change

I've added some custom elements to be included with my WooCommerce account page to be seen with the order history. Unfortunately the page is setup with tabs to only display the information pertaining to the active tab.
I'm not very familiar with jquery, but I thought it would be simple enough to use Jquery to hide the divs I added when the order history has a display of none.
I added the following script to my theme's main.js file:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
When the class .my_account_orders has a display of none it should change the div I added (.paging-nav) to have a display of none. But it just doesn't work.
Is there something wrong with this script or do I need to do something special to initiate it? Since it's in my theme's main.js file and I used $(document).ready(function() I figured it would just load with the page.
Any help with this would be greatly appreciated.
Instead of using:
var display = $('.my_account_orders');
Implement it into the if statement like this:
if($('.my_account_orders').css("display") == "none") {
Because originally it is trying to find a variable called $display, so it would return a syntax error of undefined.
You've got an errant $ in your if statement. This should work instead:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
Also keep in mind that your var display is only going to match the first element that has a class of my_account_orders, so if there are multiple elements with that class, and they don't all have the same display, you could get unexpected results.
Try this:
$(document).ready(function(){
var display = $('.my_account_orders');
if(display.css("display") == "none") {
$('.paging-nav').css("display","none");
}
});
I believe it's a very lame way to check for a css property such as display to determine if an element is hidden or not. With jquery, you can make use of :hidden selector which determines whether an element is hidden and return a bool value.
$(document).ready(function(){
if($('.my_account_orders').eq(0).is(":hidden")) // eq(0) is optional - it basically targets the 1st occurring element with class 'my_account_orders'
{
$('.paging-nav').css("display","none");
}
});
Example : https://jsfiddle.net/DinoMyte/sgcrupm8/2/

Highlighting current link

Hi I have to use only html and javascript. I have created one single page which contains a top navigation links the url for those links are something like:
domain.com,
domain.com/b1,
domain.com/b2
how do I highlight the current link.
If I understend question you may try html-attribute style for link tag:
<a style="color: red">link</a>
OR edit CSS-file for that link.
You can set class with serverside and define this class into CSS.
If coding only JS see for JS-object window.location.
You'll need to use a simple JS script to check the href of the link and compare it to the window.location.href (the current URL).
Here's a simple example using JQuery:
var currentUrl = window.location.href;
$('a').each(function(index) {
var url = $(this).attr("href");
if (url === currentUrl) {
$(this).addClass("current");
} else {
$(this).removeClass("current");
}
});
Here it adds a class current to the link if it is the current link. I have a demo here on JSFiddle.
Using jquery
$('a[href="' + window.location.pathname + '"]').addClass('highlight');
replace pathname by one property (or a combination of properties) of the location object if it's not the good one.
the snippet add 'highlight' class to the link with the specified href, then you can write some css to highlight your link.

Setting active link dynamically on static navigation

I have "navigation.html" (static coded navigtaion ) file loaded on multiple pages, using jQuery .load()
Now I need to dynamically set active <li> for each page user clicking on. I can not use body id for specific reasons.
Any other ways to do this?
If you can identify your current page by class or id (ex: body > div#contacts) for contacts.html and this class/id is unique then you have to match it with you navigation, other way is to match window.location.href value (parsed if you want) against your navigation.
changeActiveLink is defined in JS (ex:init.js) file which you include to each page
function changeActiveLink() {
var currentLocation = window.location.href;
currentLocation = currentLocation.replace('//', '/').split('/');
var page = currentLocation[currentLocation.length - 1];
if (page == "") { page = 'index.html'; }
$('#leftNav1 a[href*="'+ page +'"]').addClass('active');
}
This line is called from each file when "init.js" is included.
$('#leftNav1').load('navigation.html', changeActiveLink);
Or you can use any HTML or even HTML5 tag to specify li item.
<li class="some">
or
<li title="some">
or
<li attr-specify="some-specific-in-url">
and jQuery with window.location object
$('li[title="' + window.location.path + '"]').addClass("active");
You could set up some jquery script to get the url and then find the href of the li that matches that. This will allow you to addClass() to that li of active.
This of course will only work if your href matches the url

Categories