I need to select a navigation item as active when the page loads. This issue is within a bootstrap framework. I know how to do this in PhP.
I have multiple pages and want to keep the navigation in a PhP include. Currently, I have to have the navigation code links in each page. When the user selects "About" I want the About nav item active and dynamically selected. I would like use javascript and the "addClass" function.
I'm not a high-level javascript developer, but can do some basic functions, etc.
I have been searching and haven't found anything that works for me.
Thanks
Ted
So I'm not exactly sure what you're asking, but I assume you want the Javascript to add the .active class to a nav bar link when that url is the active one. You could create a utility function which analyzes the window's url and matches that to the correct tab. for instance:
(function(){
var host = "www.yourdomain.com/plus/whatever/else"; //the default domain
var state = window.location.href.subString(host.length - 1); //extract state
var stateMap = {
someStateName: 'nav-selector-value'
};
var navElement = document.getElementById(stateMap[state]);
navElement.className += " active"; //make sure you have a space before
})();
This is just a quick and dirty example. You'll have to use some regex if your states get more complex.
Related
First, let me explain what I am trying to accomplish. I currently have 8 small websites that are identical except for a header image and the href links.
I am looking for a way to minimize maintenance and potential for human error each time these pages need updating.
For example, say I have 2 links that point to State specific login pages.
Student Login
Teacher Login
In the past, I have been making copies of the updated HTML, then search and replace "stateId=WA" for "stateId=MI"
I started to see if I could make the URL using javascript and just append the 2 digit State ID using some function. That way I would only have to update the code, then copy it and replace the 2 digit state ID in one place, in one file.
I made progress by using the following external javascript file
function getParam() {
return 'WA';
}
function getLink() {
document.getElementById('studentLogin').href = 'https://www.mypage.com/studentLogin?stateId=' + getParam();
}
function getLink() {
document.getElementById('teacherLogin').href = 'https://www.mypage.com/teacherLogin?stateId=' + getParam();
and then using this in the HTML
CLICK ME
This worked, until I figured out that I can't have more than one element in the HTML with the same id. For example, one of the pages has a link to the Student Login in the Menu, and also has a link to the same place in the main content of the HTML, and only one of them would work.
So I suppose I could create several functions in the external javascript file each with their own ID, then update the HTML to call the new IDs, but I am in search of a better way.
All I really care about is minimizing maintenance, since I currently have 8 of these landing pages, but we could have more in the near future. Since there are only 4 distinct links off of these pages, it would be fine if I could figure out how to store the entire link in a variable, and just call that variable in the
<a> tag
Thank you for your help.
You can add classes to the relevant links, and then get the elements with document.getElementsByClassName("myclass")
test1test2
And in JS:
var links = document.getElementsByClassName("myclass")
This would make links an array containing all the links over which you could iterate to apply your modifications.
Sounds like a job for a progressive enhancement.
I would suggest you add a attribute the html link; data-state-change. Then any future links you write you just add the attribute.
//keep the base url in the tag
<a href="https://www.mypage.com/studentLogin" data-has-state>Click Me<a>
//now using jquery attach to all links that have that data- element.
$('body').on('click', '[data-has-state]', function(e){
// eat the click
e.preventDefault();
//get the url
var url = $(this).attr('href') + '?stateId=' + getParam();
window.location = url;
);
You could do something similar with a css class also instead of an html data- attribute. Then it would be.
$('body').on('click', '.someCssClass', function(e){
// eat the click
e.preventDefault();
//get the url
var url = $(this).attr('href') + '?stateId=' + getParam();
window.location = url;
);
I am using jQuery Content Panel Switcher https://code.google.com/p/jquery-content-panel-switcher/ and I use the 'show' class in on a panel to show the default panel when a page loads, but what if I want to target a different panel?
Could I pass a variable in the URL what would switch the show class to a different panel?
The plugin you're using there doesn't really have a clearly documented API, but theoretically it's possible. I'm going to show an example of how this would be done with a plugin that works the same way but is a little more solid and well-documented -- the tabs widget from jquery ui, and using hashed urls like the first comment suggests.
// simple url parser
// (via https://gist.github.com/jlong/2428561)
var url = document.createElement('a');
url.href = window.location.href;
// get the url hash as an integer
var activeTab = parseInt(url.hash) || 1;
// initialize tabs on the '.selector' element
$( ".selector" ).tabs('active', activeTab);
This way, you would be able to hash your url with the number of the tab you wanted open, and the tabs plugin would initialize with that tab open (or the first one by default). For example, if you hit http://example.com#3, the third tab would be open. If you wanted to make these words, it would be easy to add a little switch statement that mapped the numbers and strings.
An example and docs for jquery ui tabs can be found here, and the docs for the 'active' method I used in this example can be found here.
So I have a page that has multiple divs that can be toggled to be visible/invisible by the user.
Then I have another page that I want to link to something specific in the aforementioned page. How can I pass the javascript toggle code along with the link so that it displays the correct div, instead of just the default view.
You could use a url hash like site.com/page.html#div1
Then use javascript to parse the hash and decide wich div to show
var hash = window.location.hash;
var selectedDiv = hash.split('#')[1];
//Then show selectedDiv
I'm working on designing an interactive university campus map and need some direction with what I am looking to do.
Link to page: http://www.torontoclassfind.com/startpage.html
I want to be able to click on the links in the top menu (only one link is active so far and it loads and Ajax page in lower left div) and have it swap the building image with a different image to show that it's been selected.
I could do that with the following:
$("#buildinglink1").click(function () {
$("#buildingimg1").attr("src","highlightedimage.gif")
})
Problem is I need to change back the image to it's default image once another menu link is clicked and a new building is selected.
The building images are located at www.torontoclassdfind.com/building/ and the highlighted images are located at www.torontoclassdfind.com/buildingc/ and the names for the buildings are the same in both locations.
I am thinking of using JQuery's .replace element to do this (ex: jquery remove part of url) which would remove or add the 'c' to the url, but I'm kind of lost from here.
Any tips? I think I need to make a function that would indicated a link is selected and somehow merge it with the .replace element.
Just a note: .replace is a JavaScript string (and others) method, not a jQuery method.
I think you're asking to do something like this:
$(".any-building").click(function () {
//replace all building sources with the unhighlighted version
$(".any-building").attr('src', function () {
return $(this).attr('src').replace('buildingc', 'building');
});
//replace clicked image with highlighted one
$(this).attr('src', $(this).attr('src').replace('building', 'buildingc'));
});
A possible downside is that with a lot of images this swap may take a long time or cause some flicker. If that's the case, then you may want to add a class .active to the highlighted image or something like that and only do the swap for that image and the newly clicked one.
A common learning mistake in jQuery is to focus on ID's for all types of selectors. They work great for very small number of elements however become very unwieldy fast for large groups of elements that can easily be managed by simpler code methods.
You want to be able to write far more universal code where one handler would cover all of your links that share the same functionality in the page .
Example:
var $mainImage=$('#mainImage')
var $buildingLinks=$('.buildingliststyle a').click(function(){
/* "this" is the link clicked*/
/* get index of this link in the whole collection of links*/
var index=$buildingLinks.index(this);
/* perhaps all the image urls are stored in an array*/
var imgUrl= imagesArray( index);
/* perhaps the image urls are stored in data attribute of link( easy to manage when link created server side)*/
var imgUrl=$(this).data('image');
/* store the current image on display (not clear how page is supposed to work)*/
var currImage=$mainImage.attr('src');
$mainImage.data('lastImage', currImage);/* can use this to reset in other parts of code*/
/* nw update main image*/
$mainImage.attr('src', imgUrl);
/* load ajax content for this link*/
$('#ajaxContainer').load( $(this).attr('href') );
/* avoid browser following link*/
return false;
});
/* button to reset main image from data we already stored*/
$('#imageResetButton').click(function(){
$mainImage.attr('src', $mainImage.data('lastImage') );
})
Can see that by working with groups of elements in one handler can do a lot with very little code and not needing to focus on ID
Code above mentions potentially storing image url in data attribute such as:
Building name
I'm trying to make a jQuery toggle menu for a mobile website for one of my clients. I'll have to tell you i'm not experienced in javascript and i justed started looking at it.
The current website is a Wordpress website so the menu structure is generated by WP.
Because this is generated by WP i need to use javascript to manipulate the data for adding the + - and > signs for toggleing and if no childeren to go directly to the page.
I use this javascript for adding the spans with the desired icon. I've managed so far.
http://jsfiddle.net/9Dvrr/9/
But there are still 2 problems i can't seem to figure out.
Remove the href from the "a" when the "li" has a "ul" child.
This should remove the links of the items so they will only toggle (not link) to navigate straight throug to the deepest level.
Currently the javascript is adding mutiple spans with the icons. I can't seem to figure out why
I'm stuggeling with this for a while now and was wondering if someone could help me with this.
In the jsfiddle you provided, you loop on the elements to add spans with a "+" or "-" sign inside, depending on the case. The thing is, the HTML you're starting with already has those spans in it, wich is why you're seeing some duplicates.
As you said you can't add those spans in the HTML because of your WP strucutre, I guess they come from a bad copy/paste you did while creating the jsfiddle. I removed them in the HTML and added a return false to prevent linking to another page when there is a ul inside the a tag.
http://jsfiddle.net/wzzGG/
Your first problem can be solved with the following:
$.each($('#menu-mobiel li'), function(i, value) {
var $this = $(this);
if ($this.has('ul').length > 0) {
$this.children('a').attr('href','javascript:');
}
Your second problem is a bit harder for me to understand. Do you only want one + for items with submenus, and one > for items with a link?