I can't access "a" element with its href. Like this example, i need add class to element which got href="#one"
Here is jsFiddle.
jQuery:
//tabs part is working fine
$('.tabs').hide();
$('.tabs:first').show();
$('ul li a').click(function(){
var target = $(this).attr('href');
$('.tabs').hide();
$(target).fadeIn(500);
$('ul li a').removeClass('selected');
$(this).addClass('selected');
});
//problem starts when i try to reach href
var link1 = '#one';
var link2 = '#two';
var link3 = '#three';
var takE = $('ul li a').each();
var finD = take.attr('href');
finD.addClass('thisisLink1');
html:
<ul>
<li>Home</li>
<li>Posts</li>
<li>About</li>
</ul>
<div class="tabs" id="one">Home Container</div>
<div class="tabs" id="two">Posts Container</div>
<div class="tabs" id="three">About Container</div>
I have tried each method but it didn't work. I need to access elements with their attr href and set the object to addClass or animate. This way returns me as a string.
Use attribute selector like so:
$('a[href="#one"]').addClass(...)
Also note that you defined a takE variable and the you wrote take: probably you may want to write
var takE = $('ul li'),
finD = takE.find('a[href="#one"]');
finD.addClass('thisisLink1');
$('ul li a').each(function() {
if(this.href == link1) $(this).addClass('thisisLink1');
if(this.href == link2) $(this).addClass('thisisLink2');
if(this.href == link3) $(this).addClass('thisisLink3');
});
You can also use an object mapping:
var links = {
'#one': 'thisislink1',
'#two': 'thisislink2',
'#three': 'thisislink3',
};
$.each(links, function(key, val) {
$('ul li a[href="' + key + '"]').addClass(val);
});
DEMO
Related
I want to check if the current url contains the parent url to add an "active" class to the parent list item link.
jQuery(function($) {
var path = window.location.pathname;
$('ul a').each(function() {
if (this.pathname.indexOf( path )) {
$(this).addClass('active');
}
});
});
My html looks like this:
<ul>
<li><a class="list-link">Posts</a></li>
<li><a class="list-link">Blog</a></li>
<li><a class="list-link">Contact</a></li>
</ul>
When going to domain.com/contact/email I want to keep the list item to keep the "active" class.
If I understand your question correctly, you're wanting to add the active class to anchor elements in your ul list, if the anchor's text exists in the current browser path.
That can be achieved via the following (see documentation in snippet for details):
jQuery(function($) {
//var path = window.location.pathname;
var path = 'domain.com/contact/email';
// Convert path to lower case for easier matching
path = path.toLowerCase();
$('ul a').each(function() {
// Extract link label via text() method. Convert
// label to lower case for easier matching
var label = $(this).text().toLowerCase();
// Use indexOf() to check for label existing in
// path
if( path.indexOf(label) !== -1 ) {
// Add active class if match found
$(this).addClass('active');
}
});
});
.active {
background:red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<ul>
<li><a class="list-link">Posts</a></li>
<li><a class="list-link">Blog</a></li>
<li><a class="list-link">Contact</a></li>
</ul>
UPDATE
I found what I was looking for using this jQuery code:
jQuery(function($) {
var path = window.location.pathname.split( '/' )[2];
$('ul a').each(function() {
if (this.href.indexOf( path ) != -1) {
$(this).addClass('active');
}
});
});
Anchors don't have a pathname property. Change the line to check the text contained within the anchor:
if (this.textContent.indexOf( path )) {
I am cloning UL's from one element to another like so.
$( "#mobMenu li a" ).each(function(index) {
var subID = $(this).attr('id')
if (typeof(subID) !== "undefined") {
subID = "#sub_" + subID + " .subnav-menu"
var subMenu = $(subID).clone();
$(this).parent().append(subMenu);
}
});
Menu I am cloning:
<div id="sub_cat3">
<ul id="sub_cat" class="subnav-menu">
<li>..</li>
</ul>
<ul class="subnav-menu">
<li>..</li>
</ul>
</div>
Into a new mobile menu that looks like this:
<ul id="mobMenu">
<li><a id="cat3"></a>
// cloned menu to go here
</li>
</ul>
So ho can I combine each cloned ul into one UL?
<ul class="subnav-menu">
<li>..</li>
<li>..</li>
</ul>
I think you want something like this (had to contrive the HTML as a suitable example was not provided):
JSFiddle: http://jsfiddle.net/TrueBlueAussie/b10n5mf0/1/
or with your new HTML: http://jsfiddle.net/TrueBlueAussie/b10n5mf0/4/
$("#mobMenu li a").each(function (index) {
var subID = $(this).attr('id')
console.log(subID);
if (subID) {
subID = "#sub_" + subID + " .subnav-menu li"
var $div = $('<ul>').append($(subID).clone());
$(this).closest('li').append($div);
}
});
Notes:
It creates a single UL for each matching set of lists' LIs.
Only the matching LIs are cloned, then inserted under the created UL with append.
if (typeof(subID) !== "undefined") can be replaced with if (subID) as attr returns a string or undefined (and empty strings are treated as undefined by your code).
You can do...
var $subs = $('.subnav-menu'),
$lis = $subs.find('> li').clone();
// Add all the $lis to the first subnav...
$subs.eq(0).append($lis);
// Remove the rest of the subs...
$subs.slice(1).remove();
Here is a small demo: http://jsbin.com/jerapo/2/edit?js,output
My website is a parallax one page scrolling website, so all my nav links are directed to ids nested within that page...
For example:
<ul class="clearfix">
<li>Home</li>
<li>Work</li>
<li>About</li>
<li>Contact</li>
</ul>
So How would I tell my html that when someone clicks on one of these links and directs them to the corresponding ID on the page, to take on the class active? And the link that was active to turn back to the regular styling?
Assuming your link elements are contained in an element with class nav, and you're using jQuery, you could do the following:
$('.nav a').on('click', function(event) {
$('.nav a.active').removeClass('active');
$(this).addClass('active');
});
fiddle
You will have to use JavaScript to add that functionality into your application. Everytime a link is clicked, add the 'active' class to the triggering element, and remove it from all others. This is straightforward if you can use jQuery (jsFiddle with jQuery), and only a little more tedious otherwise.
$(function() {
$("ul.clearfix > li > a").click(function() {
$("a.active").removeClass("active");
$(this).addClass("active");
});
});
If you're only using native JS, you can try something along the lines of the below (jsFiddle using vanilla JS):
var links = document.getElementsByTagName("a"); // more specific selector if other links
for (var i = 0; i < links.length; i++) {
var link = links[i];
link.onclick = function () {
var prev = document.getElementsByClassName("active");
if (prev && prev[0]) {
prev[0].className = ""; // if using other classes, filter better
}
this.className += " active";
};
}
This second solution needs to be adapted to fit your particular application/DOM structure, since it's not quite as flexible as the first.
jQuery
$('ul a').on('click', function(event) {
$('a').removeClass("active");
$(this).addClass("active");
});
Replace ul a with something more specific like .nav a
$('#sidebar ul li ul li').click(function () {
var ids = $(this).attr('id');
$('#ids').addClass('active');
$('#ids').parent('ul').parent('li').addClass('has-sub active');
alert(ids); // Will alert the id if the element has one
});
I didn't understand why this is not working. alert gives me the id of the li element but the 2 lines before it don't work I mean these 2:
$('#ids').addClass('active');
$('#ids').parent('ul').parent('li').addClass('has-sub active');
Where is the problem? Am I missing something?
You need to concatenate your variable like:
$('#' + ids).
$('#ids') is looking for an element with the ID of ids. And as Blender noted in the comments, why are you doing it this way? The element you're clicking on could be referred to as simply $(this) or this. To me it might make more sense to do:
$('#sidebar ul li ul li').click(function () {
$(this).addClass('active').parent('ul').parent('li').addClass('has-sub active');
});
And you might also be able to replace .parent('ul').parent('li') with .closest('li'), but I'd need to see the HTML structure to be sure.
You are taking the id of the current element to concatenate together a selector. Instead, you can use the this keyword within the handler and use it as a reference to the clicked element. Try this:
$('#sidebar ul li ul li').click(function () {
$(this).addClass('active').closest('li').addClass('has-sub active');
});
ids is a variable which holds the id of clicked element. and in your code:
$('#ids').addClass('active');
$('#ids').parent('ul').parent('li').addClass('has-sub active');
You use ids as a string. This is not correct way. You should replace $('#ids') with $('#' + ids).
Try this:
$('#' + ids).addClass('active');
$('#' + ids).parent('ul').parent('li').addClass('has-sub active');
Did you mean to apply the new classes to the ids in the variable ids? If so you are currently applying those to elements that have the id of 'ids'. You should use the following selector: $('#'+ids).
#IshanJain #RoryMcCrossan #j08691 #EliantenHolder thank you for your response. Jquery doesnt help to solve this problem but this helper worked.
public static class HtmlHelperExtensions
{
public static string ActivePage(this HtmlHelper htmlHelper,string controller, string action)
{
string _classValue="";
string _currentController = htmlHelper.ViewContext.Controller.ValueProvider.GetValue("controller").RawValue.ToString();
string _currentAction = htmlHelper.ViewContext.Controller.ValueProvider.GetValue("action").RawValue.ToString();
if (_currentController == controller && _currentAction == action)
{
_classValue = "active";
}
else if (_currentController == controller && action.Equals(""))
{
_classValue = "has-sub active";
}
else
{
if (action.Equals(""))
{
_classValue = "has-sub";
}
}
return _classValue;
}
}
and this is from my layout page
<li class="#Html.ActivePage("Order","")">
<a href="javascript:;" class="">
<span class="icon-box"> <i class="icon-dashboard"></i></span> Sipariş Açma
<span class="arrow"></span>
</a>
<ul class="sub">
<li class="#Html.ActivePage("Order","Index")"><a class="" href="#Url.Action("Index","Order")">Sipariş</a></li>
<li class="#Html.ActivePage("Order","orderProduct")"><a class="" href="#Url.Action("orderProduct","Order")">Ürün Sipariş</a></li>
<li class="#Html.ActivePage("Order","orderCloth")"><a class="" href="#Url.Action("orderCloth","Order")">Kumaş Sipariş</a></li>
<li class="#Html.ActivePage("Order","orderAccessory")"><a class="" href="#Url.Action("orderAccessory","Order")">Aksesuar Sipariş</a></li>
</ul>
</li>
I have a standard ul-based CSS navigation menu. I'm trying to use Jquery to toggle the active menu css class name. However, I'm encountering two issues:
The window.location.href never equals any of my anchor hrefs. I switched to pathname, but they still do not match each other. Even though in the debugger they appear to.
I cannot seem to get the li from it's anchor.prev. I need to change the class name on the li.
Here's the html:
<div id="left-content">
<ul>
<li class="separator">Main
<ul>
<li class="active link">Main 1</li>
<li class="link">Main 2</li>
<li class="link">Main 3</li>
</ul>
</li>
<li class="separator">Tools
<ul>
<li class="link">Tools 1</li>
</ul>
</li>
</ul>
</div>
When an anchor is clicked, it's corresponding li should have "active link" as the class name. And all other li's should be reset to just "link" as the class name.
Here's the Jquery javascript:
function toggle_active_menu() {
$('#left-content a').each(function() {
/*var isActive = $(this).attr('href') == window.location.href;*/
var active = this.pathname == window.location.pathname;
var prev = this.prev();
alert("active: " + active + "\nthis.pathname: " + this.pathname + "\nwindow.location.pathname: " + window.location.pathname + "\nprev: " + prev);
prev.toggleClass('active', active);
});
}
I put the alert in there to help debug. As I mentioned, the clicked anchor's href (or pathname) never matched the window's location href (or pathname). And prev is always undefined instead of being the li of the anchor.
Eventual Answer
After testing the various answers, I fould that I had to remove the onclick calls and call the toggle_active_menu function in the document ready function instead. The window location was not being updated before onclick was being called. Also, I did not use toggleClass so that I could preserve the order of the class names.
function toggle_active_menu() {
$('#left-content ul li ul li a').each(function() {
var pathname = window.location.pathname == '/' ? '/main1' : window.location.pathname;
var active = pathname.indexOf(this.pathname) != -1;
if (active) {
$(this).parent().attr('class', 'active link');
} else {
$(this).parent().attr('class', 'link');
}
});
}
To get the li which is the parent of a element use parent method and toggleClass take only the calss to toggle. To compare the href of the anchor with window.location.href you can use indexOf method.
function toggle_active_menu() {
$('#left-content a').each(function() {
var isActive = (window.location.href.toLowerCase().indexOf($(this).attr('href')) != -1);
$(this).parent().toggleClass('active');
alert("active: " + isActive);
});
}
Simplified version for you.
$('.link').click(function(){
$('.link').removeClass('active');
$(this).addClass('active');
})
toggleClass only takes one paramater it should be
prev.toggleClass('active');
To fix getting a handle on the correct LI to toggle the class, try
var prev = $(this).parent();
For the pathname, try using $(this).attr("href") and matching it against window.location.href, or checking if it's contained within window.location.href