Calling a JS script in HTML - javascript

Hello there I have this code and I want to display active links in purple. I have that in a js file however, does not seem to work as expected. I am not sure where exactly I am doing wrong. Everything else is working properly but when you clink a link it fails to highlight to purple as is in the css. I have provided the necessary code only, Anyone?
html
<html>
<head>
<link href="site.css" rel="stylesheet"> <script src="color.js"></script>
</head>
<body>
<div class="nav-container">
<ul class="navigation-menu">
<li><a href='start.php'>Home</a></li>
<li><a href='pay.php'>C2B Payments</a> </li>
<li><a href='sms.php'>C2B SMS</a></li>
<li><a href='#'>B2C Payments</a>
<ul>
<li> B2C Payments</li>
<li> Make Payments</li>
</ul>
</li>
<li><a href='bsms.php'>B2C SMS</a></li>
<li><a href='index.php'>Log Out</a></li>
</ul>
</div>
</body>
</html>
css (site.css)
.navigation-menu li.active a {
background-color: purple;
color:#fff;
}
.navigation-menu li ul {
display: none;
}
.navigation-menu li a:hover{
background-color:black;
color: white;
}
.navigation-menu li a.active {
background-color: purple;
color:#fff;
}
javascript (color.js)
$(document).ready(function(){
$('ul li a').click(function(){
$('li a').removeClass("active");
$(this).addClass("active");
});
});

You have two problems.
First, you haven't included jQuery on the page, so when the JS runs, it throws an error because $ isn't defined.
If you were to fix then this would be the order of events:
The link is clicked
The JavaScript starts running
The JavaScript modifies the DOM of the page
The JavaScript finishes
The browser follows the link
The page with the modified DOM is discarded
A new page is loaded
… and the new page hasn't been modified by the JavaScript.
Put the active class in the HTML of the new page.

You have to check the page url and match href in the element and add class active to respective element
You have to include jQuery Lib
Replace test.html page2.html by the name of page u have
$(document).ready(function() {
var pageURL = $(location).attr('href'),
pageName= [ /test.html/, /page2.html/, /page3.html/],
links = $('a'),
LinksToActive;
for( var i=0; i < $(pageName).size(); i++){
for( var j=0; j < $(links).size(); j++){
var str = $(links[j]).attr('href');
if( 'str:contains(pageName[i])' ){
LinksToActive = $(links[j]);
break;
}
else{
continue
}
}
}
$(LinksToActive).addClass('active');
});
Change/ Add page name in pageName variable nad this script just before closing of body tag

Related

jQuery Highlight Nav Item on Load

I'm new to HTML/CSS/JS and I'm doing some testing and fiddling around with stuff and decided to highlight a nav element when on that page. I decided to use jQuery for this because from what I read it was the easiest solution. It's worked great so far, but my issue is that it doesn't highlight the main "chat" page on load because it's just the url, without the /index.html. I'd appreciate any help on how to get it to add the active class to the index.html element on load.
HTML:
<aside>
<nav>
<ul>
<li>Chat</li>
<li>Friends</li>
<li>Settings</li>
</ul>
</nav>
</aside>
JQuery:
jQuery(function($) {
var path = window.location.href;
$('aside nav ul li a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
SCSS:
.active {
border-right: 10px solid $accent-two;
}
First, your pathname includes the entire URL, so it will never match with href in your a tag. You need to get just the page name.
Next, you should check for the href attribute of the a tag and not the href itself.
The example below uses a dummy link to aid as a demo. I had to add in the href in JS because of the snippet.
jQuery(function($) {
var path = window.location.pathname;
var page = path.split("/").pop();
//
// The line below is for demo on stackoverflow purposes
$("#forDemoOnStackPurpose").attr("href", page);
//
$('aside nav ul li a').each(function() {
if ($(this).attr("href") === page) {
$(this).addClass('active');
}
});
});
.active {
border-right: 10px solid red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<aside>
<nav>
<ul>
<li><a id="forDemoOnStackPurpose" href="">This test page</a></li>
<li>Chat</li>
<li>Friends</li>
<li>Settings</li>
</ul>
</nav>
</aside>
I give you an example of how i will dot it. Note that i had to simulate location change with some code, but every time you run the example, it will highlight a different anchor tag.
$(document).ready(function()
{
// Simulate change on "windows.location.href"
//===========================================================
var paths = ["/index.html","/friends.html","/settings.html"];
var idx = Math.floor(Math.random() * 3) + 0;
console.log("Random idx = " + idx);
//===========================================================
var path = paths[idx];
//var path = window.location.href;
$("a").removeClass('active');
$("a[href='" + path + "']").addClass('active');
});
.active {
border-right: 10px solid blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<aside>
<nav>
<ul>
<li>Chat</li>
<li>Friends</li>
<li>Settings</li>
</ul>
</nav>
</aside>

Change url doesn't change tab selected

I was implementing that if i refresh the page, it should make active to previously selected tab(preserve selected tab) . So I Create a simple html page and add some jQuery.
But if i change URL manually like file:///home/2.html#news to file:///home/2.html#home
it changes only content of page but doesn't change tab ,that was selected. .
Here is my code.
<body>
<ul>
<li id="first">Home</li>
<li id="second">News</li>
<li id="third">Contact</li>
<li id="forth">About</li>
</ul>
<p id="home">
home section
</p>
<p id="news">
news section
</p>
<p id="contact">
contact section
</p>
<p id="about">
about section
</p>
</body>
<style>
p{
display: none;
}
:target {
display:block;
border: 2px solid #D4D4D4;
background-color: #e5eecc;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
if(localStorage.getItem("active_state") == null ){
activeStateId = "first";
}
else{
activeStateId = localStorage.getItem("active_state")
}
$('#'+activeStateId).addClass('active');
$('li').click(function(){
$('.active').removeClass('active');
$(this).addClass('active');
localStorage.setItem("active_state", $(this).attr('id'));
});
});
</script>
When you got link hashes, you dont actually reload the page, but the browser just triggers those links. You rely on CSS :target change rule which evaluates every time the #hash changes on the url.
p {
display: none;
}
:target {
display:block;
border: 2px solid #D4D4D4;
background-color: #e5eecc;
}
Thus, you have all the sections updated properly even without refreshing the page. In order to have such functionality, you don't need to store any data to the local or remote machine since you are using hashes on the url. Just use the hashes and handle the hashchange event to add the .activate class to the links like this:
$(document).ready(function() {
var hash = window.location.hash;
if(hash.length > 0) {
hash = hash.substring(1);
$('li a[href$='+hash+']').parent().addClass('active');
}
$(window).on('hashchange', function() {
$('.active').removeClass('active');
var hash = window.location.hash
if(hash.length > 0) {
hash = hash.substring(1);
$('li a[href$='+hash+']').parent().addClass('active');
}
});
});
Check my working example here: http://zikro.gr/dbg/html/urlhash.html#about

Change the selected list element in a navigation list using plain JavaScript

I have trouble in writing a script to change the appearance of the clicked tab in a webpage navigation list. In other words, I want to make the clicked tab appear as the selected (in code). I tried to do that by changing its id to selected_link and restoring the id of the previously selected tab.
EDIT: Following jamespaned's suggestion, I replaced element IDs with classes.
My tabs appear like in this picture:
So, when I click to "bio", I want it to appear as "home" and "home" to appear as the other tabs.
As I'm a newbie in JavaScript coding, I didn't managed to accomplish that. Here is what I've done:
The HTML code for the (inline) navigation list:
<nav>
<ul id="navlist">
<li class="selected"> home </li>
<li class=""> bio </li>
<li class=""> publications </li>
<li class=""> software </li>
<li class=""> contact </li>
</ul>
</nav>
its respective CSS:
nav ul {
list-style:none;
padding:0;
margin:0;
}
nav li {
background-color:black;
display:inline;
border:solid;
border-width:1px 1px 0 1px;
margin:0 5px 0 0;
}
nav li a {
color:white;
padding:0 10px;
}
.selected {
background-color:white;
padding-bottom: 1px;
}
.selected_link{
color:blue;
}
and the JavaScript which I've designed to accomplish this task, but it didn't worked:
function changeSelected(clickedId)
{
var ulist = document.getElementById("navlist");
var elems = ulist.getElementsByTagName("class");
for (var i = 0; i < elems.length - 1; i++)
{
var sel = elems[i].getAttribute("class");
if (sel == selected)
{
var selli = elems[i];
break;
}
}
selli.setAttribute("class", "");
selli.lastElementChild.setAttribute("class", "");
var clicked = document.getElementById(clickedId);
clicked.setAttribute("class", "selected_link");
clicked.parentNode.setAttribute("class", "selected");
}
How could I do that using only plain JavaScript?
This Javascript will do what you want:
function changeSelected(clickedId)
{
var selli = document.getElementById("selected");
var sela = document.getElementById("selected_link");
sela.setAttribute("id", "");
selli.setAttribute("id", "");
var clicked = document.getElementById(clickedId);
clicked.setAttribute("id", "selected_link");
clicked.parentNode.setAttribute("id", "selected");
}
That said, here are some ideas that might help your Javascript education:
You are using Javascript to set your IDs, but the Javascript won't work on the next page after you've clicked on one of the links. You'll probably need to do some backend (PHP/Ruby, etc) coding to get your styles to change.
IDs are normally used to refer to a unique element on the page that doesn't change, such as a #header or #sidebar_banner. You might want to use a class instead, such as ".selected_link".
You don't need both #selected_link and #selected. You could do ".selected" and ".selected a" to change the CSS so you only need to change one element.
Hope that helps!

Change link color of the current page with CSS

How does one style links for the current page differently from others? I would like to swap the colors of the text and background.
HTML:
<ul id="navigation">
<li class="a">Home</li>
<li class="b">Theatre</li>
<li class="c">Programming</li>
</ul>
CSS:
li a{
color:#A60500;
}
li a:hover{
color:#640200;
background-color:#000000;
}
With jQuery you could use the .each function to iterate through the links with the following code:
$(document).ready(function() {
$("[href]").each(function() {
if (this.href == window.location.href) {
$(this).addClass("active");
}
});
});
Depending on your page structure and used links, you may have to narrow down the selection of links like:
$("nav [href]").each ...
If you are using URL parameters, it may be necessary to strip these:
if (this.href.split("?")[0] == window.location.href.split("?")[0]) ...
This way you don't have to edit each page.
a:active : when you click on the link and hold it (active!).
a:visited : when the link has already been visited.
If you want the link corresponding to the current page to be highlighted, you can define some specific style to the link -
.currentLink {
color: #640200;
background-color: #000000;
}
Add this new class only to the corresponding li (link), either on server-side or on client-side (using JavaScript).
It is possible to achieve this without having to modify each page individually (adding a 'current' class to a specific link), but still without JS or a server-side script. This uses the :target pseudo selector, which relies on #someid appearing in the addressbar.
<!DOCTYPE>
<html>
<head>
<title>Some Title</title>
<style>
:target {
background-color: yellow;
}
</style>
</head>
<body>
<ul>
<li><a id="news" href="news.html#news">News</a></li>
<li><a id="games" href="games.html#games">Games</a></li>
<li><a id="science" href="science.html#science">Science</a></li>
</ul>
<h1>Stuff about science</h1>
<p>lorem ipsum blah blah</p>
</body>
</html>
There are a couple of restrictions:
If the page wasn't navigated to using one of these links it won't be
coloured;
The ids need to occur at the top of the page otherwise the
page will jump down a bit when visited.
As long as any links to these pages include the id, and the navbar is at the top, it shouldn't be a problem.
Other in-page links (bookmarks) will also cause the colour to be lost.
JavaScript will get the job done.
Get all links in the document and compare their reference URLs to the document's URL. If there is a match, add a class to that link.
JavaScript
<script>
currentLinks = document.querySelectorAll('a[href="'+document.URL+'"]')
currentLinks.forE‌​ach(function(link) {
link.className += ' current-link')
});
</script>
One Liner Version of Above
document.querySelectorAll('a[href="'+document.URL+'"]').forEach(function(elem){elem.className += ' current-link'});
CSS
.current-link {
color:#baada7;
}
Other Notes
Taraman's jQuery answer above only searches on [href] which will return link tags and tags other than a which rely on the href attribute. Searching on a[href='*https://urlofcurrentpage.com*'] captures only those links which meets the criteria and therefore runs faster.
In addtion, if you don't need to rely on the jQuery library, a vanilla JavaScript solution is definitely the way to go.
a:link -> It defines the style for unvisited links.
a:hover -> It defines the style for hovered links.
A link is hovered when the mouse moves over it.
include this! on your page where you want to change the colors save as .php
<?php include("includes/navbar.php"); ?>
then add a new file in an includes folder.
includes/navbar.php
<div <?php //Using REQUEST_URI
$currentpage = $_SERVER['REQUEST_URI'];
if(preg_match("/index/i", $currentpage)||($currentpage=="/"))
echo " class=\"navbarorange/*the css class for your nav div*/\" ";
elseif(preg_match("/about/*or second page name*//i", $currentpage))
echo " class=\"navbarpink\" ";
elseif(preg_match("/contact/* or edit 3rd page name*//i", $currentpage))
echo " class=\"navbargreen\" ";?> >
</div>
N 1.1's answer is correct. In addition, I've written a small JavaScript function to extract the current link from a list, which will save you the trouble of modifying each page to know its current link.
<script type="text/javascript">
function getCurrentLinkFrom(links){
var curPage = document.URL;
curPage = curPage.substr(curPage.lastIndexOf("/")) ;
links.each(function(){
var linkPage = $(this).attr("href");
linkPage = linkPage.substr(linkPage.lastIndexOf("/"));
if (curPage == linkPage){
return $(this);
}
});
};
$(document).ready(function(){
var currentLink = getCurrentLinkFrom($("navbar a"));
currentLink.addClass("current_link") ;
});
</script>
Best and easiest solution:
For each page you want your respective link to change color to until switched, put an internal style in EACH PAGE for the VISITED attribute and make each an individual class in order to differentiate between links so you don't apply the feature to all accidentally. We'll use white as an example:
<style type="text/css">
.link1 a:visited {color:#FFFFFF;text-decoration:none;}
</style>
For all other attributes such as LINK, ACTIVE and HOVER, you can keep those in your style.css. You'll want to include a VISITED there as well for the color you want the link to turn back to when you click a different link.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html><head>
<style type="text/css"><!--
.class1 A:link {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 4px solid #333333; border-right: 4px solid #333333; border-top: 3px solid #333333; border-bottom: 4px solid #333333;}
.class1 A:visited {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 4px solid #333333; border-right: 4px solid #333333; border-top: 3px solid #333333; border-bottom: 4px solid #333333;}
.class1 A:hover {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #0000FF; border-right: 3px solid #0000FF; border-top: 2px solid #0000FF; border-bottom: 2px solid #0000FF;}
.class1 A:active {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #0000FF; border-right: 3px solid #0000FF; border-top: 2px solid #0000FF; border-bottom: 2px solid #0000FF;}
#nav_menu .current {text-decoration: none; background:#1C1C1C url(..../images/menu-bg.jpg) center top no-repeat; border-left: 3px solid #FF0000; border-right: 3px solid #FF0000; border-top: 2px solid #FF0000; border-bottom: 2px solid #FF0000;}
a:link {text-decoration:none;}
a:visited {text-decoration:none;}
a:hover {text-decoration:none;}
a:active {text-decoration:none;}
--></style>
</head>
<body style="background:#000000 url('...../images/bg.jpg') repeat-y top center fixed; width="100%" align="center">
<table style="table-layout:fixed; border:0px" width=100% height=100% border=0 cellspacing=0 cellpadding=0 align=center><tr>
<td style="background: url(...../images/menu_bg-menu.jpg) center no-repeat;" "border:0px" width="100%" height="100%" align="center" valign="middle">
<span class="class1" id="nav_menu">
<font face="Georgia" color="#0000FF" size="2"><b> Home </b></font>
<font face="Georgia" color="#0000FF" size="2"><b> FAQs page </b></font>
<font face="Georgia" color="#0000FF" size="2"><b> About </b></font>
<font face="Georgia" color="#0000FF" size="2"><b> Contact </b></font>
</span>
</td></tr></table></body></html>
Note: the style goes in between the head tag (<head> .... </head>) and the class="class1" and the id="nav_menu" goes in the ie: (-- <span class="class1" id="nav_menu"> --).
Then the last class attribute (class="current") goes in the hyper-link code of the link in the page that you want the active current link to correspond to.
Example: You want the link tab to stay active or highlighted when it's correspondent page is whats currently in view, go to that page itself and place the class="current" attribute by it's link's html code. Only in the page that corresponds to the link so that when ever that page is at view, the tab will stay highlighted or stand out different from the rest of the tabs.
For the Home page, go to the home page and place the class in it. example: <a href="http://Yourhomepage-url.com/" class="current" target="_parent">
For the About page, go to the about page and place the class in it. example: <a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" class="current" target="_parent">
For the Contact page, go to the contact page and place the class in it. example: <a href="http://Yourhomepage-url.com/youraboutpage-url.php_or_.html" class="current" target="_parent">
etc ......
Notice the example Table above;- Lets assume this was the Home page, so on this page, only the Home url link section has the class="current"
Sorry for any meaning-less error, am not a prof. but this worked for me and displays fine in almost all the browsers tested, including ipad, and smart phones. Hope this will help some-one out here because is very frustrating to want to and not able to. I had tried so had to get to this, and so far it's good for me.
#Presto
Thanks! Yours worked perfectly for me, but I came up with a simpler version to save changing everything around.
Add a <span> tag around the desired link text, specifying class within. (e.g. home tag)
<nav id="top-menu">
<ul>
<li> <span class="currentLink">Home</span> </li>
<li> About </li>
<li> CV </li>
<li> Photos </li>
<li> Archive </li>
<li> Contact</li>
</ul>
</nav>
Then edit your CSS accordingly:
.currentLink {
color:#baada7;
}
You do not need jQuery just to do this! All you need is a tiny and very light vanilla Javascript and a css class (as in all the answers above) :
First define a CSS class in your stylesheet called current.
Second add the following pure JavaScript either in your existing JavaScript file or in a separate js script file (but add script tage link to it in the head of the pages) or event just add it in a script tag just before the closing body tag, it will still work in all these cases.
function highlightCurrent() {
const curPage = document.URL;
const links = document.getElementsByTagName('a');
for (let link of links) {
if (link.href == curPage) {
link.classList.add("current");
}
}
}
document.onreadystatechange = () => {
if (document.readyState === 'complete') {
highlightCurrent()
}
};
The 'href' attribute of current link should be the absolute path as given by document.URL (console.log it to make sure it is the same)
Use single class name something like class="active" and add it only to current page instead of all pages. If you are at Home something like below:
<ul id="navigation">
<li class="active">Home</li>
<li class="">Theatre</li>
<li class="">Programming</li>
</ul>
and your CSS like
li.active{
color: #640200;
}
You can add an id in addition to the class name. Styles referring to the id will override the styles referring to the class. You might call the id: #active and add it to the link of the html page you are currently on:
HTML of href="/" (Home):
<ul id="navigation">
<li id="active "class="a">Home</li>
<li class="b">Theatre</li>
<li class="c">Programming</li>
</ul>
Css:
li a{
color:#A60500;
}
li a:hover{
color:#640200;
background-color:#000000;
}
#active {
color:#640200;
background-color:#000000;
}
So for example if you are trying to change the text of the anchor on the current page that you are on only using CSS, then here is a simple solution.
I want to change the anchor text colour on my software page to light blue:
<div class="navbar">
<ul>
<li>Home</li>
<li>Useful Sites</li>
<li class="currentpage">Software</li>
<li>The Workbench</li>
<li>Contact</li></a>
</ul>
</div>
And before anyone says that I got the <li> tags and the <a> tags mixed up, this is what makes it work as you are applying the value to the text itself only when you are on that page. Unfortunately, if you are using PHP to input header tags, then this will not work for obvious reasons.
Then I put this in my style.css, with all my pages using the same style sheet:
.currentpage {
color: lightblue;
}

Change color of an anchor when clicked

i want that when i click this link its color changes to the given color
<li id="press">Press</li>
The CSS declaration :active will accomplish what you're after. http://www.w3schools.com/CSS/pr_pseudo_active.asp
Example.
a:active {
color: #C00;
}
NB.
a:active MUST come after a:hover in the CSS definition in order to be effective!
Here is the sample Css for the visited hyperlink
a:link {color:#FF0000}
a:visited{color:Red}
Hope that will help.
All links? a:focus { color: orange; }
Some links? Give them a class, eg <a class="foo" ...>: a.foo:focus { color: purple; }
One link? Give it an id, eg <a id="bar" ...>: a#bar:focus { color: #BADA55; }
You can accomplish that at server-side with PHP or with JS.
With PHP all you need is to added a given classname to the link once clicked.
a very simple example would be:
<a href="myURL" class="<?php if(ExpressionToDetermineIfLinkIsClicked) echo 'selected'; ?>">
and CSS:
.selected { color: #FF0000; }
If you would like to do it with JS , and you are using any JS Framework just search the frameworks' site for "How to add an event" & "How to add classname" then combine what you get to know from the search results.
If you are, by coincidence, using prototype.js framework,
then you can try the following:
function selectLink(link){
link.addClassName('selected');
var otherLinks = link.siblings();
for(var i = 0; i < otherLinks.lenght; i++){
otherLinks[i].removeClassName('selected');
}
}
document.observe('dom:loaded', function(){
$('menu').observe('click', function(event){
event.stop();
var link = Event.element(event);
selectLink(link);
});
});
---
<div id="menu">
<a href="url1" id="link1" class="">
<a href="url2" id="link2" class="">
<a href="url3" id="link3" class="">
</div>

Categories

Resources