compare url string and menu string then add class using jquery - javascript

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

Related

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

JQuery to highlight current menu item

I am working on a website and in that i have few menu links. I want to highlight the current menu items based on the url. Currently i have the following code in my JQuery:
$(document).ready(function () {
debugger;
$('#menu a').each(function (index) {
if (this.href.trim() == window.location.href)
$(this).addClass("current");
});
});
Its working fine only when there is no query string present in the url. When i pass some query string into the url then this JQuery is not working.
You want location.pathname if you don't want the querystring.
This uses filter() to return just the relevant link(s)...
$("#menu a").filter(function (index) {
return this.href.search(location.pathname) !== -1;
}).addClass("current");

loop through if, return if false, if true => stop if

So I got the following scenario:
$('.menu').find('a').each( function(el, val) {
if( window.location.hash !== val.hash ) {
$('.menu li').first().addClass('active') // we found no valid hash for us, so set first <li> active
$('#hash1').show() // and show the first content
} else {
$(this).parent().addClass('active') // we found an hash, so give its parent <li> an active class
$(window.location.hash).show() // can be #hash2, #hash3, whatever
return false; // since we found something, stop the if.
}
});
Well now obviously, each time we found no valid hash, we set the first element active and show the first content... but I dont want that.
I want the if to loop through all elements first before we go into the else statement.. and THEN if we found nothing, set the first element active and show the first content.
since I am looping through each "a", how do I do that?
Just keep a variable outside of the loop:
var found = false;
$('.menu').find('a').each( function(el, val) {
if( window.location.hash === val.hash ) {
$(this).parent().addClass('active'); // we found an hash, so give its parent <li> an active class
$(window.location.hash).show(); // can be #hash2, #hash3, whatever
found = true;
}
});
if(!found) {
$('.menu li').first().addClass('active'); // we found no valid hash for us, so set first <li> active
$('#hash1').show(); // and show the first content
}
Also, semicolons at the end of statements are not optional.
You can use .filter() to get the elements you want. If none are selected, you perform the default action:
var $links = $('.menu').find('a').filter(function() {
return window.location.hash === this.hash;
});
if($links.length > 0) {
$links.parent().addClass('active');
$(window.location.hash).show();
}
else {
$('.menu li').first().addClass('active');
$('#hash1').show();
}
Reference: .filter
If you could explain your requirement more clearly in English I think you'll find the JavaScript structure would follow naturally.
The following is my best guess at what you are trying to do: All anchors in ".menu" that have the same .hash as window.location.hash should have their parent li made "active" and the corresponding element shown. If none matched then the first menu item should be made "active" and "#hash1" shown.
var matched = false;
$('.menu').find('a').each( function(el, val) {
if( window.location.hash === val.hash ) {
matched = true;
$(this).parent().addClass('active');
$(window.location.hash).show();
}
});
if (!matched) {
$('.menu li').first().addClass('active');
$('#hash1').show();
}
var elm = $(window.location.hash).length ? window.location.hash : '#hash1';
$(elm).show();
$('a[href$="'+elm+'"]').parent().addClass('active');
Assuming the markup is the same for #hash1 as the rest, and that there is only one hash in the browser adress bar (or none) ?

Javascript if else problems mobile Jquery toggle menu

I'm trying to make a jquery toggle menu for a mobile website.
I've managed to create a toggle menu with + and - when toggled and when not
Current version: http://jsfiddle.net/9Dvrr/7/
Now i'm trying to create a if else statement fot displaying a ">" when there are no children.
Experiment: http://jsfiddle.net/9Dvrr/6/
Problem is that i just can seem to figure it out..
Thanks in advance,
Rick
You need to check the length property when checking if it has children. Otherwise, all you're checking is if the result is non-null or not...and it will always be non-null even if the selector doesn't match because it will return jQuery. It will be empty of any elements, but an object nonetheless and thus non-null.
if (element.has('ul').children('a').length > 0) {
element.prepend("<span>+ </span>");
This code below will do what you want, but it could definitely use a little refactor. It's mostly to show you how you can achieve it simply :
$('#menu-mobiel ul').hide();
$.each($('#menu-mobiel li'), function(i, value) {
var $this = $(this);
if($this.find('ul a').length > 0) {
$this.find('a').append("<span>+ </span>")
.addClass('plus')
.click(function() {
togglePlus($(this));
$(this).next('.sub-menu').slideToggle('normal');
});
}
else
{
$this.find('a').append("<span>> </span>");
}
})
function togglePlus(element) {
element = $(element);
if (element.hasClass('plus')) {
element.removeClass('plus').addClass('minus');
element.children('span').text('- ');
} else {
element.removeClass('minus').addClass('plus');
element.children('span').text('+ ');
}
}

Categories

Resources