Add a class to the current active link using YUI - javascript

I got this function in jQuery:
jQuery(function() {
jQuery('.primary-nav li').each(function() {
var href = jQuery(this).find('a').attr('href');
if (href === window.location.pathname) {
jQuery(this).addClass('current');
}
});
});
but unfortunately I need to do accomplish the same with the YUI library. Add a class to the a element if the a href is the same as the current active page.
Thanks a lot!

An alternative:
YUI().use('node', function(){
Y.all('.primary-nav li').each(function(node){
var href = node.getAttribute('href');
node.toggleClass('current', href === window.location.pathname);
});
});
Adds the class if the second parameter is true, otherwise removes it.

An almost direct translation of the JQuery above would be something like:
YUI().use('node', function(){
Y.all('.primary-nav li').each(function(node){
var href = node.getAttribute('href');
if (href === window.location.pathname){
node.addClass('current');
}
});
});
However, I would imagine you could do something like:
YUI().use('node', function(){
Y.one('.primary-nav li a[href="' + window.location.pathname + '"]').addClass('current');
});
To achieve the same effect. (code tested only in my head)

Related

How to add an active class to an anchor tag based on URL and Vanity URLs?

I have this working minus the part if the URL is www.mysite.com/home/. It works if it is www.mysite.com/home/index.aspx, but not if you take off the index.aspx. It also works for all other pages I have - page2.aspx, page3.aspx, etc...
Also, I might do a URL rewrite on the pages (so page2.aspx would be page2 and page3.aspx would be page3)
How do I adjust the below code to be able to add the class active to the active page.
jQuery:
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
$("nav a").each(function(){
if($(this).attr("href") == pgurl || $(this).attr("href") == '')
$(this).addClass("active");
})
});
HTML where the class is added:
<nav class="clearfix">
Home
Page2
Page3
</nav>
You can simply check for window.location.pathname
$(function() {
$("nav a").each(function(){
if($(this).attr("href") == window.location.pathname || window.location.pathname == '')
$(this).addClass("active");
})
});
If you want to find the link with the same url part that you are looking for you can try this:
var lookup = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
$("a:regex(href, .*"+ lookup +".*)").addClass('active');
Holy Cow figured out how to do the no index! I didn't think this was going to be so hard to get an answer on. Still not sure on the vanity bit. Might do separate post on that.
$(document).ready(function() {
// Add active class to menu
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/")+1);
$("nav a").each(function(){
if($(this).attr("href") == pgurl)
$(this).addClass("active");
if (pgurl == '')
$("nav a:first-child").addClass("active");
})
});
});
Try this
var s = window.location.href.substr(window.location.href.lastIndexOf("/")+1);
if(!s)
document.querySelector("nav > a:first-child").className = "active";
else
document.querySelector("nav > a[href*='"+s+"']").className = "active";
I know, maybe this is stupid solution, but:
var current_url = window.location.hash.substr(1);
$('.news #' + current_url).addClass('active');

Removing active class if clicking active link a second time?

I came across a question that wanted to add an active link to the currently clicked menu item.
The solution was to add:
$("a").click(function(){
$("a").removeClass("active");
$(this).addClass("active");
});
Now how can we remove the active class if we click the active link a second time? I'm guessing we need to use toggleClass() but I haven't been able to make it work. Note only one link should have active class at a time.
Here is a demo: http://jsfiddle.net/A6dqQ/
You can do:
$('a').click(function(e){
e.preventDefault();
var $a = $(this);
$a.toggleClass('active').siblings().removeClass('active');
});
Use toggleClass() then:
$(this).toggleClass("active");
Code:
$("a").click(function(){
$(this).toggleClass("active");
$("a").not(this).removeClass("active");
});
FIDDLE DEMO
Check if current link is active then add/remove active class based on that, Try this:
$("a").click(function(){
var $this = $(this);
var isActive = $this.hasClass('active');
$("a").removeClass("active");
isActive ? $this.removeClass("active") : $this.addClass("active");
});
jsFiddle
here you have a simple answer:
$("a").on("click", function() {
$("a").removeClass("active");
$(this).addClass("active");
});
$("nav").on("mouseleave", function() {
$("nav").find("a").removeClass("active");
});
What this does is, when your mouse leaves the nav it will automatically remove you active class on a. here you have the DEMO
Something like this?
$("a").click(function () {
var $this = $(this);
if ($this.hasClass("active")) {
$this.removeClass("active");
} else {
$("a").removeClass("active");
$this.addClass("active");
}
});
Fiddle

Add class to several elements

I have a cloned element and I want it so if I add a class to one of them it checks for active removes is and adds it to this and translates to the other. Here's what I'm working with:
$(document).ready(function() {
$("li").click(function(){
/*Here I want to add something like var active = $(.clonedelement + this, this)
but that does probably not makes sense, so what should i do? */
var active = $(this)
// If this isn't already active
if (!$(this).hasClass("active")) {
// Remove the class from anything that is active
$("li.active").removeClass("active");
// And make this active
active.addClass("active");
}
});
});
Right now, it removes the current active from both, not does only add class to one.
I made a jsfiddle of it
http://jsfiddle.net/pintu31/8BxuE/
function UpdateTableHeaders() {
$(".persist-area").each(function() {
var el = $(this),
offset = el.offset(),
scrollTop = $(window).scrollTop(),
Header = $("#headerny", this)
if ((scrollTop > offset.top) && (scrollTop < offset.top + el.height())) {
Header.addClass("floatingHeader");
} else {
Header.removeClass("floatingHeader");
};
});
}
// DOM Ready
$(function() {
$(window)
.scroll(UpdateTableHeaders)
.trigger("scroll");
});
If you just need to highlight the clicked element with the class of active, and remove all others then try this:
$("li").click(function(){
$("li").removeClass("active");
$(this).addClass("active");
});
You don't really need to check if either this, or others already have the class, simply steamroller to 'active' class off all the others and add it to the one that's been clicked
try this
demo updated 1
demo updated 2 //with clone(true)
demo updated 3 //with clone(false) - default
demo updated 4
$(document).ready(function() {
$(document).on('click', 'li', function(){
var ind = $(this).index();
$('li').removeClass('active');
$('li').eq(ind).addClass('active');
$('#header1').empty();
$('#header').find('ul').clone(true).appendTo( '#header1' );
});
});
$(document).ready(function() {
$("li").click(function(){
$("li").removeClass("active");
// And make this active
$(this).addClass("active");
}
});
});

Jquery not selecting proper href's

This script:
$(function() {
$('a').each(function() {
var href = $(this).attr('href');
if ("a:not(http://)") {
$(this).attr('href', '/' + href);
}
});
});
Add the slash to every link even links with the contain "http://" Not sure why? I do not get any errors?
Any ideas on how I can fix this?
You mixed up two things:
jQuery selectors:
$(function() {
$('a:not([href^="http://"])').each(function() {
var href = $(this).attr('href');
$(this).attr('href', '/' + href);
});
});
and pure javascript if statements:
$('a').each(function() {
var href = $(this).attr('href');
if (href.substr(0, 'http://'.length) == 'http://'){
$(this).attr('href', '/' + href);
}
});
Both do the same.
Note that they will generate invalid links for other schemes than http (e.g. /https://example.com/index.html). Depending on how clean the HTML code you're working with is, you may simply look for the colon to identify absolute links:
$(function() {
$('a:not([href*=":"])').each(function() {
var href = $(this).attr('href');
$(this).attr('href', '/' + href);
});
});
First, you code is equal to the following
$(function() {
$('a').each(function() {
var href = $(this).attr('href');
if(true) { $(this).attr('href', '/' + href); }
});
});
if you really want to update href based on condition, if statetment should be different:
$(function() {
$('a').each(function() {
var href = $(this).attr('href');
if(href.indexOf('http://') == -1 ) { $(this).attr('href', '/' + href); }
});
});
Another way would be the one offered by #Yogu, where you simple don't loop for links which you are not going to update
Just a addon to Yogu,
Remember that your in the context of each tag. "Inside the object itself".
So, you can access the href directly.
$('a').each(function() {
if (this.href.substr(0, 'http://'.length) == 'http://'){
this.setAttribute('href', '/' + href);
}
});

jQuery changing attribute and changing it back

I want to make all links on the page unaccessible until the user clicks a button.
$('a').attr('href','#');
$("#button-yes").click(function(){
$('a').attr('href',function(){
$(this).attr('href');
});
});
How about just keeping track of state instead of rewriting all the hrefs?
var buttonClicked = false;
$('a').click(function(){
if(! buttonClicked) {
return false;
}
});
$("#button-yes").click(function(){
buttonClicked = true;
});
Have a var outside your function that says something like:
button_clicked = false;
Then use this to disable all links
$('a').click(function(){
if(!button_clicked){
return false;
}
});
Returning false will cause the link to do nothing.
The simplest example would be to hijack the click event of all links:
$('a').live('click.disable', function() {
return false;
});
$("#button-yes").click(function() {
$('a').die('click.disable');
});
(see this fiddle: http://jsfiddle.net/A6QPn/) but anyone can right-click the link and open it in new tab or something like that.
Another example would be to store the href attributes as data and restore them later:
$('a').each(function() {
var $this = $(this);
$this.data('href', $this.attr('href'));
$this.attr('href', '#');
});
$("#button-yes").click(function() {
$('a').each(function() {
var $this = $(this);
$this.attr('href', $this.data('href'));
});
});
(see this fiddle: http://jsfiddle.net/eQDdQ/) and here the links are just not working because they all point to '#' on the current page.
Another example would be to basically do the same but remove the href attribute altogether making the links look like normal text until the button is clicked:
$('a').each(function() {
var $this = $(this);
$this.data('href', $this.attr('href'));
$this.removeAttr('href');
});
$("#button-yes").click(function() {
$('a').each(function() {
var $this = $(this);
$this.attr('href', $this.data('href'));
});
});
(see this fiddle: http://jsfiddle.net/gmLTP/)
You need to stash the value of the href so that it can be recovered later. I'll stash the href value into the rel attribute.
$('a').each(function(){
$(this).attr('rel', $(this).attr('href')); //store the href values
$(this).attr('href', ''); //clear the href values
});
$("#button-yes").click(function(){
$('a').each(function(){
$(this).attr('href', $(this).attr('rel')); //recover the href values
});
});
This is a simple approach, but it leaves the address in the rel attribute. A clever user might find and use this to circumvent your button, so here's another approach as suggested by #rsp.
$('a').each(function(){
$(this).data('link', $(this).attr('href')); //store the href values
$(this).attr('href', ''); //clear the href values
});
$("#button-yes").click(function(){
$('a').each(function(){
$(this).attr('href', $(this).data('link')); //recover the href values
});
});
By storing the href using .data(), the link address is a little more obscure so users shouldn't be able to circumvent the button as easily (though disabling JavaScript will sidestep this completely).

Categories

Resources