Find if current windows.pathname contains location to li a href - javascript

I have this code to add an active class on the link to the current page:
jQuery(function() {
jQuery('.topmenu li').each(function() {
var href = jQuery(this).find('a').attr('href');
if (href === window.location.pathname) {
jQuery(this).find('a').addClass('active');
}
});
});
This works great for matching exactly the pathname, but how can I see if the page I'm on, is a subpage for a link?
When I have a link like this: Sub page 1 the code works.
When Im on /top-page-1/sub-page-1/, but when I'm on /top-page-1/sub-page-1/sub-sub-page-1/, I don't get an active class on the link. Is there any way to this?

try this in your code:
jQuery(function() {
jQuery('.topmenu li').each(function() {
var href = jQuery(this).find('a').attr('href');
if (window.location.pathname.indexOf(href)>-1) {
jQuery(this).find('a').addClass('active');
}
});
});

Related

i need to delete target attribute from anchor if its value is null

For the sake of W3c validation i need to remove target attribute from all anchors where target value is null
i had following code inside body
<div>
home emput
home
home empty
home
</div>
Here is my script
$(document).ready(function () {
var target = []
var i = 0;
$("body a").each(function () {
target[i++] = $(this).attr("target");
if($(this).attr("target") == ""){
$(this).removeAttr("target");
}
});
console.log(target);
});
This code is working fine when I view console empty targets are removed. But when I view the source (Ctrl+u), targets are still there,
I just want to delete them.
Try this, its working
$(document).ready(function () {
var target = []
var i = 0;
$("body a").each(function () {
target = $(this).attr("target");
if(target == "")
{
$(this).removeAttr("target");
}
});
//console.log(target);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
home emput
home
home empty
home
</div>
As you are using "$", I assume you have jQuery
$("a[target='']").each(function() {
$(this).removeAttr("target");
});
https://jsfiddle.net/6g6t60pa/
try this to remove..
$('a[target=""]').removeAttr('target');
but you cannot achieve this while considering W3 Validation, it grabs page content without executing JS, so the best practice is to hide it using server side script(PHP).

Anchor link to content inside hidden div

I'm trying to link to content from an external page, using
<a name="anchor"></a>
and
The content where the anchor is located is hidden inside a drawer, using jQuery:
$(".toggle_container").hide();
See fiddle: http://jsfiddle.net/bd1mbu5j/1/
I've tried wrapping my head around the method found here, but I know there's something I'm missing.
window.onload = function() {
var hash = window.location.hash; // would be "#div1" or something
if(hash != "") {
var id = hash.substr(1); // get rid of #
document.getElementById(id).style.display = 'block';
}
};
Also should be noted, I'm not just trying to open the drawer, but link to specific content within certain drawers.
See this fiddle http://jsfiddle.net/bd1mbu5j/2/
$(".toggle_container").hide();
$("h3.trigger").click(function(){
var _this = this;
$(this).toggleClass("active").next().slideToggle("normal", function () {
var anchor = $(_this).data('anchor');
console.log(anchor);
if (anchor && $('#'+anchor).length) {
console.log($('#'+anchor).offset().top);
$('html, body').animate({scrollTop: $('#'+anchor).offset().top+'px'});
}
});
return false; //Prevent the browser jump to the link anchor
});
I added the target element id as a data attribute and picked that up once the slide toggle was finished. Then I animated down to that element if it exists.

JavaScript to highlight active page

I am trying to utilize JavaScript to highlight the current page. I have a main menu and a sub menu on the page. I want the highlighted main menu to look different from the sub menu. Here is the JavaScript I came up with the apply a css class to the current page. How do I get the JavaScript to differentiate the two different classes?
<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(function(){
$('a').each(function() {
if ($(this).prop('href') == window.location.href) {
$(this).addClass('main_current');
}
});
});
</script>
<script>
$(function(){
$('a').each(function() {
if ($(this).prop('href') == window.location.href) {
$(this).addClass('sub_current');
}
});
});
</script>
It really depends on the page/code structure you're going for. I usually don't check window.location, but instead set rel attribute on the page body. On homepage body will have rel="home", on some other page rel='other-page and so forth.
This way you can check for body's rel attribute and change menu/submenu's status based on that.
(function(){
var currentLocation = $('body').attr('rel');
switch(currentLocation){
case 'home':
//add class to the home link
break;
case 'other-page':
//add class to the other link
break;
}
})();
Specify better the selector when you iterate over the submenu and override some properties with 'sub_current'. EG:
If you have
<ul id="menu">
<li>ThisMenu
<ul id="sub-menu">
<li>ThisSubMenu</li>
</ul>
</li>
</ul>
you could specify with $('#sub-menu a').
I hope it helps.
cheers
The method below will do the same thing
$(function() {
var url = document.location.href;
if (url.indexOf("about") > -1) {
$('#nav-bar ul li:contains("About")').addClass('sub_current');
}
else if (url.indexOf("index") > -1) {
$('#nav-bar ul li:contains("Home")').addClass('main_current');
}
else {
// do something else
}
});
Note: :contains selctor is case sensitive.

Open page based on $(this) selector

I'm modifying a wordpress site and have a menu with four anchor tags (buttons) to the left of a slider. When a user selects a button, the slide associated with the button shows. Now, I'd like to open a page when the user clicks the button, instead of showing the slide. Here is the code so far:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$a = $(this);
$(this).showSlide();
if($a.id == $('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Here I'm testing to see if I can click on the anchor with the id '#slide-1285' and log it to the console. It always says 'not testing'. I'm going to set up conditions for all id's so a user is redirected to the correct page. Something like this:
$('#slidernavigation > a').on('click', function(e){
e.preventDefault();
$(this).showSlide();
if($a.id == $('#slide-1285')){
window.location.href = "http://webpage1";
}
elseif($a.id == $('#slide-1286')){
window.location.href = "http://webpage2";
}
elseif($a.id == $('#slide-1287')){
window.location.href = "http://webpage3";
}
else($a.id == $('#slide-1288')){
window.location.href = "http://webpage4";
}
});
Any ideas? Thanks in advance.
To get the id of the element that was clicked, you can do:
$(this).attr('id');
That will return a string. So you could do:
if($(this).attr('id') === 'slide-1285') { do something }
$('#slide-1285') would return a jquery element, but you want just the id. I think the code above is more what you are looking for.
You can add a new data attribute to each of your link and then get that value and redirect.
<a data-webpage="http://webpage1" href="whatever" id="slide-123"></a>
<a data-webpage="http://webpage2" href="whatever" id="slide-456"></a>
.....
and then
// this will bind all ids starting with slide-
$('[id^=slide-]').on('click', function(e){
// some code.
window.location.href = $(this).data('webpage');
}
1) you are comparing $a.id, that is string, to object $('#slide-1285');.
2) To simplify:
$(document).ready(function(){
$('.a').click(function(e){
e.preventDefault();
window.location = $(this).attr('href');
});
});
<a href='http://google.com' class='a'>Google!</a><br/>
<a href='http://stackoverflow.com' class='a'>SO!</a><br/>
jQuery objects have no id property. You need to do attr('id'), or just get the id property of the plain DOM object. Additionally, jQuery objects are never going to equal each other. Third, you want to check if the clicked element has a certain ID, which can be done using .is().
In sum, you could do one of these:
Comparing strings:
$('#slidernavigation > a').on('click', function(e){
if(this.id == '#slide-1285'){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Using .is():
$('#slidernavigation > a').on('click', function(e){
if($(this).is('#slide-1285')){
console.log('testing');
}
else{
console.log('not-testing');
}
});
Or, just let the browser do its thing. Give your <a>s href attributes, and they'll function as links, even without JS.
instead of writing $.id
you should write
$a.attr('id')
and this should be checked like this :-
if( $a.attr('id') == slide-1285)
not the way you are doing :)
Try
var pages = [{"slide-1285" : "http://webpage1"}
, {"slide-1286" : "http://webpage2"}
, {"slide-1287" : "http://webpage3"}
, {"slide-1288" : "http://webpage4"}
];
$('#slidernavigation > a').on('click', function(e) {
e.preventDefault();
var nav = e.target.id;
$.grep(pages, function(page) {
if (nav in page) {
window.location.href = page[nav];
}
})
});
jsfiddle http://jsfiddle.net/guest271314/2nf97dfr/
<div id="a">
dhjdfd
</div>
$('#a').on('click',function(e){
var clickedElement= e.srcElement;
if($(clickedElement).attr("id") == "abc"){
//do something
}
});
just use e.srcElement to get the element reference and then get its id.. and btw u can use switch case rather than multiple if else statements ..
working fiddle link

compare url string and menu string then add class using jquery

I have a URL which looks like this:
http://www.website.co.uk/en-us/aboutus/thegroup/test.aspx
I have a UL LI menu on the page:
<ul>
<li>Test</li>
<li>Hello</li>
<li>Bye</li>
<li>Something</li>
<li>Cars</li>
</ul>
I am having the menu on every page and would like to use jquery to check that im on that page. If i am then make the A/li bold so the user knows they are on the page.
I have tried the following:
$(document).ready(function () {
if(window.location.href.indexOf("test")) //
{
alert("your url contains the name test");
}
});
But id like something that doesnt involve hard coding the values of the URL string. As if the user decides to add more links to the UL/LI the jquery needs to check the link and the url automatically and add a class to the LI (so that i can style it).
Hopefully thats enough infomation.
The issue is because the indexOf() method returns -1 when the value is not found. You need to check for that value, not coerce the result to a boolean as you currently are. Try this:
$(document).ready(function () {
var loc = window.location.href;
$("ul a").each(function() {
if (loc.indexOf($(this).attr("href")) != -1) {
$(this).addClass("current");
}
});
});
You would need to make the selector a bit more specific, something like #menu a
This?
$('ul#menu a').each(function() {
if(window.location.href.indexOf($(this).attr('href')) !== -1) {
$(this).closest('li').addClass('yourClass');
}
});
I added an id menu to your ul to basically differentiate your menubar with other uls that may be in the same page. also !== -1 as indexOf returns -1 if it can't find the string searched in the argument.
indexOf returns -1 if the string is not contained:
(document).ready(function () {
if(window.location.href.indexOf("test") != -1) //
{
alert("your url contains the name test");
}
});
$(document).ready(function () {
var liTest = $('ul > li'); // ' was missing
liTest.each(function() {
if(window.location.href == $('a', this).attr('href')) //
{
$(this).css('font-weight', 'bold');
return;
}
});
});

Categories

Resources