Highlight a button based on location - javascript

I'm trying to highlight a navigational button (in a menu) based on the page being viewed. Here is what I have so far:
var loca = String(document.location.href);
// Get document location and specific page.
if (loca) {
if(loca.search(RegExp("((/[\w]*)\.php)")) != -1) {
activate(loca.match(RegExp("((/[\w]*)\.php)").split("/").join("")));
} else {
activate("home");
}
}
// Activate a button
function activate(bName) {
$(".button[name=" + bName + "]").css({
"border-left": "1px solid white",
"border-right": "1px solid white"
});
}
What I want to happen is this:
Get URL of page
Get the specific file name of page, and if not found, then we are on the homepage.
Using jQuery, I try to find the name of the button, and if the name matches the filename, then highlight it.
Thing is, this only highlights the "Home" button. What am I doing wrong? Also, if you have any suggestions on how I can better accomplish this, please let me know!

I would get the filename like this, instead:
var pathname = window.location.pathname.split("/");
var filename = pathname[pathname.length-1].split(".")[0];
alert(filename);

Your regular expression is incorrect.
var loc_match = window.location.href.match(/(\w+)\.php/);
activate(loc_match ? loc_match[1] : "home");

I don't have a solution but I would assume the regex is flawed. Did you try to store the result in a variable and console.log it?

I've actually implemented something like this. Here's my code:
var currentPage = window.location.pathname.toLowerCase().split('/').reverse()[0].split('#')[0].split('?')[0];
if (!currentPage || currentPage == '')
{
currentPage = 'default.aspx';
}
$('#nav li').removeClass('current').each(function() {
var href = $(this).find('a').first().attr('href');
if (href && href.toLowerCase().indexOf(currentPage) >= 0)
{
$(this).addClass('current');
}
});
This takes into account any query strings or searches may be in the URL. Using reverse() may not be the most efficient way of doing it, but it certainly works.

When you declare your regexp as new RegExp object, you have to use double backslash escaping symbols (instead one backslash, when you just assign literal like var a = /\w/i; );
So, your code should work after some reg exp correction:
var loca = document.location.href;
var pattern = new RegExp("[\\w]*(?=\\.php)","i");
// Get document location and specific page.
if(pattern.test(loca)) {
activate(pattern.exec(loca));
} else {
activate("home");
}
// Activate a button
function activate(bName) {
$(".button[name=" + bName + "]").addClass('active')
}
And as already said, it's easier to assign class to your active element.

Related

Alter URL #ID with JQuery button

I'm trying to create a function where, on every button click, the ID at the end of the pages URL is added to by 1. So,
example.org/page -> (buttonclick) -> example.org/page#1 -> (buttonclick) -> example.org/page#2 etc. etc.
What I've got at the moment is:
var anchor = 0;
$('#bottom-right').click(function() {
var anchor += 1;
var anchorurl = "#" + anchor;
var currenturl = window.location.href;
var newurl = currenturl.slice(0, -1) + anchorurl;
window.location.replace(newurl);
});
But it doesn't really work & I imagine there is a cleaner solution...
Thanks in advance.
simply make it
$('#bottom-right').click(function() {
window.location.hash = ++anchor;
});
Make use of the built-in hash method.
So basically the url contains #.So you can also track this # and get the next number and increment it.
Code example:
var hashValue = window.location.href.substring(window.location.href.indexOf('#')+1);
window.location.hash = hashValue + 1;

Display Image Based on URL Ending (Variable or Attribute) [Pound/Number Sign # ]

I need an image to be displayed based on the ending of a URL.
For example, I need "123.jpg" to be displayed when someone visits:
website.com/view/#123
website.com/view/#123.jpg
website.com/view#123
website.com/view#123.jpg
(whichever is recommended or would actually work)
I'm looking for the end result to be: < img src=123.jpg" >
Thanks in advance. I will sincerely appreciate any assistance.
(By way of background or additional information, I need this for Facebook's sharer.php so that people can share one of hundreds of images on a given webpage (for example, website.com/blog and they happen to love the 123rd image on there), they click the link to share that specific image (123.jpg), and then any of their friends who clicks on the link (website.com/view/#123) will arrive at a themed page with just the image in the middle (123.jpg) and nothing else, and then they can click around the rest of the website. The main benefit is that 123.jpg will be the only image that shows up as a thumbnail on the Facebook Feed or "Wall".)
window.onhashchange = function() {
if (location.hash) {
var url = location.hash.substr(1); // strip the # char
if (url.indexOf('.') == -1) {
url += '.jpg';
}
document.getElementById('myImg').src = url; // show the image; value of the variable 'url'
}
};
window.onhashchange(); // call the event on load
Use something like this.
$(document).ready(function(){
var url = document.URL; //get the url
if ( url.indexOf("#") != -1 ) //check if '#' is present in the url
{
var split_array = url.split("#");
var image_url = split_array[split_array.length - 1];
//display the image
}
});
Try this out,
$(document).ready(function() {
getImageSrc();
$(window).on('hashchange', getImageSrc); // will always lookout for changes in # URL
});
function getImageSrc() {
if(window.location.hash) {
var imgSrc = window.location.hash.substr(1);
if(imgSrc.indexOf('.') == -1 ) {
imgSrc = imgSrc + ".jpg";
}
alert(imgSrc);
}
}

Class of ID Change based on URL - URL Based Image Swap -

What I'm trying to achieve:
Based on URL (ie., foo.com/item1), the div element "logoswap" receives a different class.
The following is the code I put together but it seems completely wrong. I'm not a JS pro by any means, XHTML/CSS is more my speed (some PHP)... I cannot use PHP, even if it is possible in PHP (and I know it is because I have a PHP version of what I need done already, but I can't call the PHP properly.
I'm really just trying to get a different logo to show up based on the directory/url... It doesn't have to be a background element called in by the CSS class necessarily, I just need a different image to load based on the aforementioned url variable...
$(function() {
var url = location.pathname;
if(url.indexOf('item1') > -1) {
document.getElementById("logoswap").className += " class1";
}
elseif(url.indexOf('item2') > -1) {
document.getElementById("logoswap").className += "class2";
}
elseif(url.indexOf('item3') > -1) {
document.getElementById("logoswap").className += "class3";
}
elseif(url.indexOf('item4') > -1) {
document.getElementById("logoswap").className += "class4";
}
elseif(url.indexOf('item5') > -1) {
document.getElementById("logoswap").className += "class5";
}
else {
document.getElementById("logoswap").className += "class1";
}
});
That's what I have... Ugly I'm sure.
That's why I'm here though, I definitely need some help.
Assigning CSS Class By URL Pathname
A jsfiddle has been setup for
this solution.
Here is a case for using numeric expressions if they are available. This does not apply to the above question.
$(function() {
var rgx = /item(\d+)$/,
url = location.pathname,
id = (rgx.test(url)) ? url.match(rgx)[1] : '1';
$("#logoswap").addClass("class" + id);
});
UPDATE:
In light of the new details you may need an array of values, these should be derived from or exactly equal to the class names you intend to use.
$(function(){
// my favorite way to make string arrays.
var matches = "brand1 brand2 brand3".split(" "),
url = location.pathname.match(/\w+$/)[0], // get the last item
id = matches.indexOf(url),
className = matches[(id > -1) ? id : 0];
$("#logoswap").addClass(className);
});
To make this work you will need a few things in place. I will assume that the paths will end in a number as we have outlined here. The default ends with 1. You will need the images to be accessible. You need to define the styles for each possibility.
CSS Setup
#logoswap {
height : 200px;
width : 200px;
}
.class1 {
background-image : url(/path/to/default.jpg);
}
.class2 {
background-image : url(/path/to/second.jpg);
}
.brand1 {
background-image : url(/path/to/brand/1/logo.jpg);
}
...
Without jQuery
if you do not have jQuery in your code you may need to use window.onload.
(function(){
var old = window.onload;
window.onload = function(){
old();
var r = /item(\d+)$/,
url = location.pathname,
id = (r.test(url)) ? url.match(r)[1] : '1';
document.getElementById('logoswap').className += "class" + id;
};
})()
I just want to take a moment here to
encourage anyone who is doing this
type of code to get used to Regular
Expressions and learn them. They are
far and away the most frequently used
cross language part of my development
arsenal.
There's nothing that wrong with what you have. You could tidy it up with something like below.
$(function() {
var url = location.pathname;
var logo = document.getElementById("logoswap");
var i = 6;
logo.className = "class1";
while(i--)
{
if(url.indexOf("item" + i) > -1) {
logo.className = "class" + i;
}
}
});
Hope this helps.
Using just HTML/CSS, you could add (or append via javascript) an id to the body of the page:
<body id="item1">
Then in your CSS, create a selector:
#item1 #logoswap {
// class1 CSS
}

Code isn't compatible with IE?

$(document).ready(function() {
var url = document.location.toString();
$('.tab').click(function() {
if($(this).is(".active")) {
return;
}
var classy = $(this).attr("class").split(" ").splice(-1);
var innerhtml = $('.content.'+classy).text();
$('#holder').html(innerhtml);
$('.tab').removeClass('active');
$(this).addClass('active');
});
var url = document.location.toString();
if(url.match(/#([a-z])/)) {
//There is a hash, followed by letters in it, therefore the user is targetting a page.
var split = url.split("#").splice(-1);
$('.tab.'+split).click();
}
else {
$('.tab:first').click();
}
});
Hey, I was just informed by one of my commenters that this code doesn't work in IE. I can't for the life of me figure out why. Whenever you switch tabs, the content of the tab doesn't change. Meanwhile the content of the #holder div is all the tabs combined.
Any ideas?
Not the answer you're after, but I'd seriously recommend looking into the jQueryui tabs widget if you can. It's made my life a lot easier dealing with this stuff at least.
Hard to tell without an IE version and a page to look at what exactly is happening- but here are some best guesses:
change:
if($(this).is(".active")) {
to:
if($(this).hasClass("active")) {
change:
var innerhtml = $('.content.'+classy).text();
to:
var innerhtml = $('.content .'+classy).text(); // note the space
change:
var url = document.location.toString();
to:
var url = document.location.hash;
I did all changes which Ryan suggested except adding the space between '.content' and the period as it is needed. He could not have known without the source code.
I changed your .splice(-1) to [1] so that I'm choosing the second item in the array, which is the class name. It looks like .splice(-1) is behaving differently in IE and other browsers.
I have tested the code with IE 7-8 and it works.
Source code as it is now:
$(document).ready(function() {
var url = document.location.hash;
$('.tab').click(function() {
if ($(this).hasClass("active")) {
return;
}
var classy = $(this).attr("class").split(" ")[1];
var innerhtml = $('.content.' + classy).text();
$('#holder').html(innerhtml).slideDown("slow");
$('.tab').removeClass('active');
$(this).addClass('active');
});
if (url.match(/#([a-z])/)) {
//There is a hash, followed by letters in it, therefore the user is targetting a page.
var split = url.split("#")[1];
$('.tab.' + split).click();
}
else {
$('.tab:first').click();
}
});

Javascript to redirect from #anchor to a separate page

I have a set of links with #anchors pointing to a single webpage and I would like to smoothly move to a model with a separate webpage for each of those links. I want the old links to keep working using a redirect.
Old link style:
/all_products#A
/all_products#B
/all_products#C
New link style:
/products/A
/products/B
/products/C
I know that the server does not receive the #anchor name in the request but Javascript might.
Is it possible to automatically redirect from /all_products#A to /products/A using Javascript?
JQuery would be fine, it's being used on the site anyway.
I added this new answer to include some best practices for both extracting the hash from the url and doing a redirect.
// Closure-wrapped for security.
(function () {
var anchorMap = {
"A": "/products/A",
"B": "/products/B",
"C": "/products/C"
}
/*
* Best practice for extracting hashes:
* https://stackoverflow.com/a/10076097/151365
*/
var hash = window.location.hash.substring(1);
if (hash) {
/*
* Best practice for javascript redirects:
* https://stackoverflow.com/a/506004/151365
*/
window.location.replace(anchorMap[hash]);
}
})();
Put this as close to the top of your HTML <head> as you can so that it can execute before the rest of the page resources download:
<script>
function checkURL() {
var old_path = '/all_products';
if (window.location.pathname != old_path) {
// Not on an old-style URL
return false;
}
// Some browsers include the hash character in the anchor, strip it out
var product = window.location.hash.replace(/^#(.*)/, '$1');
// Redirect to the new-style URL
var new_path = '/products';
window.location = new_path + '/' + product;
}
checkURL();
</script>
This will check the current page URL and redirect if it matches the old-style path.
This code makes use of the window.location object which contains all the parts of the current URL already split up into component parts.
Making this script more generic is left as an exercise for the implementer.
I hope this can help :)
var urlSplit = document.URL.split("#");
if (urlSplit[1]) {
location.href = "http://www.example.org" + "/" + urlSplit[1];
}
else {
location.href = "http://www.example.org";
}
With jquery, either just replace the href with the correct one:
$('a').each(function() {
this.href = this.href.replace(/all_products#/, 'products/');
});
or capture clicks and redirect:
$('a').click(function() {
window.location = this.href.replace(/all_products#/, 'products/');
return false;
});
this might help:
A
B
C
D
E
<script type="text/javascript">
function redirectMe(a){
var aa=a+"";
window.location=aa.replace(/#/g,"/");
}
</script>

Categories

Resources