How to style the current page differently in the main navigation? - javascript

Say I have a basic website with a navbar that has a few links. When I am on a page (say, Terms of Use), I want the "Terms of Use" link in the navbar to be highlighted. When I switch to a different page, I want that page's link to be highlighted (i.e. I switch to privacy page, and then "Privacy" is highlighted in the navbar).
Does anyone know a simple way to do this with HTML/CSS/JS?

A simple way to do it without using javascript or php etc would be to add a different class to the body tag on each page.
<body class="nav-1-on">
Then in your css file:
body.nav-1-on a.nav-1, body.nav-2-on a.nav-2 { color:red )
SO you need XXX classes for however many nav items you have and you put a class on each nav item too as illustrated.
Make sense?

Update (brain fade, had wrong selector). For CSS3 browsers, you can easily target the page name itself:
a[href*=pageNameImOn.htm] {color: red;}
The *= will here match all href paths that include pageNameImOn.htm in them, which would match:
<a href="/my/path/to/file/pageNameImOn.htm">
<a href="/pageNameImOn.htm">
<a href="/pageNameImOn.htm#interalJumpLink">

For the link that you want to be a different color, you can manually set the style
<a style="color:red">My link is red</a>
Probably a better way to do would be to define a class where the color is red
<style> .visited { color:red } </style>
and then for the actual link
<a class="visited">My red link</a>

This solution uses jQuery, jQuery is just a compiled code library for javascript really, offering easy to use snippets and functionalities.
The is definitely the easiest way of achieving what you're after, although it is "client-side" so the class will be added by the users machine, rather than being added by the server and then sent to the user. But for smaller sites, it should suffice.
What is happening: This code finds your navigation, here it is looking for the li of .nav, so replace ('.nav li') with whatever your menu class is called, so possibly: ('.mymenu li'). It then sees if the menu link matches the current page, if it does, it adds a class to the li. So you also need to create a class of .active, such as: .active{background-color:blue;}
Hope this helps!
<script type="text/javascript" charset="utf-8">
$(document).ready(function() {
jQuery('.nav li').each(function() {
var href = jQuery(this).find('a').attr('href');
if (href === window.location.pathname) {
jQuery(this).addClass('active');
}
});
});
</script>

Just for the fun of it.
What about a Single page and CSS3 only solution, without any backend code or Javascript:
<ul>
<li><a id="home" href="#home">Home</a></li>
<li><a id="terms" href="#terms">Terms of use</a></li>
</ul>
CSS
li a { color: black; }
#home:target { color: red; }
#terms:target { color: red; }
The :target selector in CSS will match an ID selector that matches the current hash-tag.
Here's some more information: http://reference.sitepoint.com/css/pseudoclass-target
Pretty good support in Firefox, Safari, Opera and Chrome.
Incomplete support in IE9 and IE10:
IE doesn’t react to the Back and Forward buttons: the element doesn’t apply or remove the pseudo-class at all. http://www.quirksmode.org/css/contents.html

Set a different id on your body to identify the page.
<body id="terms-of-use">
an example nav:
<nav>
<a class="home" href="#">Home</a>
<a class="terms-of-use" href="#">Terms</a>
</nav>
then in your css:
nav a {
// default style
background: blue;
}
#terms-of-use a.terms-of-use {
// if the id of body is terms-of-use then the link with the class .terms-of-use...
background: red;
}

Related

jQuery/CSS - Whole Div Clickable, on hover activate a tag hover state

I'm trying to make the .wrapper div a clickable link that goes to the a.icon location. Also, when they hover over the .wrapper div the a.icon:hover state actives, not just when you hover over the icon itself.
Any help would be great.
This is what I have so far:
jQuery(document).ready(function($) {
$(".aca-question-container").hover(function() {
$(".icon").trigger("hover");
});
$(".aca-question-container").click(function(){
window.location=$(this).find("a").attr("href");
return false;
});
});
Example: http://jsbin.com/diyewivima/1/edit?html,css,js,output
In HTML5, you can wrap block elements such as your .wrapper div, within anchors. This is a rudimentary version of what I think you're looking for: http://jsbin.com/qegesapore/edit?html,css,js,output
I removed the JS you had there as I'm not sure it's necessary, and obviously some styling will be needing to be tweaked.
There shouldn't be any requirement for JS to achieve this really.
The hover state can still be applied to the icon as per:
.your-anchor:hover .icon {
background: #666;
}
As I commented, you can use jQuery and a class to achieve what you want. Below is the JS: (it must be inside the onload function)
$('div#wrapper').mouseenter(function(){
$('a.icon').addClass('hover');
});
$('div#wrapper').mouseleave(function(){
$('a.icon').removeClass('hover');
});
And, you must not forget, in your CSS you have to replace a.icon:hover with a.icon:hover, a.icon.hover, so that it emulates the hover state when the class is added. Like this:
a.icon:hover, a.icon.hover{
//CSS GOES HERE
}
For the CSS portion- propagating the hover is pretty easy. Just use .wrapper:hover .icon
as the hover effect selector. You can drop .icon:hover, too, since the parent is hovered when the child is hovered.
As for propagating the click down to it... also easy without jQ.
.wrapper:hover .icon{
color:#f00;
}
<div class="wrapper" onclick="this.getElementsByClassName('icon')[0].click()">
icon
testit
</div>
The error generated is the "there's not stackoverflow.com/google.com" error, showing that the link was followed. Slap https:// in front of the href and pull it out of an iframe and you'll be able to fully see it works.
EDIT:
bsod99's fix is cleaner. So long as you can rearrange the DOM and don't need to support ancient relics (pre-HTML5 spec browsers, like Firefox <3.5) (which you probably don't have to do), use his instead.

How to simulate click on a display:none on hover image (how to listen for any mouse click in a browser)

On a website (find it by the link) I have links with images in footer (screenshot)
I have found a great glitch effect in a footer icons which I want to use. It chages images randomly if code looks like that:
<footer class="footer text-center">
<a target="_blank" href="http://link1.com"><img src="f2.jpg"></a>
<img src="f3.jpg">
<a target="_blank" href="http://link3.com"><img src="f1.jpg"></a>
<a target="_blank" href="http://link4.com"><img src="f5.jpg"></a>
<a target="_blank" href="http://link5.com"><img src="bc.png"></a>
<img src="mail.jpg">
</footer>
and simple style
.footer img:hover {
display:none;
}
But in that scenario click while hovering on of the image footers gives no result.
I've tried to use javascript:
var a_href
$("footer a").on("mousemove", function() {
a_href = $(this).attr('href');
console.log(a_href);
});
$(document).click(function(){
console.log("!!!!!!!!!!!");
console.log(a_href);
window.open(a_href,'_blank');
});
Idea was to save the last hovered link and then emulate the click on it by clicking any other element. But that method works only if I click anywhere ELSE than a space over the glitchy icons. Same with $('body').click, $('.footer').click.
I've tried to overlay footer with other div on which i'd be putting .click but then display:none on hover doesn't work.
Here is a jsfiddle - http://jsfiddle.net/yssdjr17/1/
What should I do? Thank you.
UPD
If we use something instead of a display:none we loose the cool glitch effect that way. We loved how randomly elements collapsed and that user might click on one of the elements, but never sure on which one. Some sort of a minigame for him.
Is there a way to listen for a mouseclick, in browser, no matter on what element?
Don't use display: none, use visibility: hidden instead. This way the element will still be there, just not visible.
.footer img:hover {
visibility: hidden;
}
JSFiddle demo.
The effect makes it look broken.
You can't fire the click event from anything hidden or not displayed.
Instead try:
<div id="awesomelink" onclick="openawesomewindow('http://link1.com');"></div>
#awesomelink
{
height:60px;
width:60px;
background-image:url('f1.jpg');
}
#awesomelink:hover
{
background-image:url('awesomecrazyanimated.gif');
}
It's how I'd do it and you'll get a more consistant result across different browsers.
Also the menu of icons won't be shortened by one element making savvy surfers afraid to click.

Single page application routing w/ Crossroads & Hasher, by example

I am trying to write my first single-page application. The idea is to have 1 HTML file that contains many <div> tags; where each <div> represents a single web "page". Then the application just shows 1 <div> at a time, and hides the others. In this way, as users navigate my app, I'm really just showing/hiding different "page" divs, and giving the illusion of a single page app.
Additional requirements are:
This is an HTML5 app
Each page div must map too its own bookmarkable URL (http://myapp.example.com/#fizz, http://myapp.example.com/#buzz, etc.)
Singe each page div is bookmarkable, the app must work with the HTML5 history api
I decided on using Crossroads for routing, and Hasher for History. The other lead contender was AngularJS, but in the end I decided against AngularJS because it was too heavyweight for what I'm trying to do here, and seemed to have a steeper learning curve associated with it.
So far, my project has the following directory structure:
myapp/
index.html
myapp.js
myapp.css
signals.min.js <-- Required by both Crossroads and Hasher
crossroads.min.js
hasher.min.js
The JSFiddle containing my index.html, myapp.css and myapp.js files is here:
http://jsfiddle.net/Sxfms/2/
The idea is that the user can click one of the links in the "navbar" ("Home", "About", "Contact") and be brought to the "page" (div) representing that particular page.
As you can see, the default "page" should be HOME, meaning this is the only div you should be able to see. But all the page divs are visible, and none are hidden. And until I can get the page divs showing/hiding correctly, I can't really test routing/history functionality. Have I configured Crossroads/Hasher wrong somehow?
I think there is a solution for your requirements. It is a really easy, lightweight approach without the need of any javascript just with the power of CSS. ;-)
The key of the whole approach is the CSS pseudo-class selector :target.
So let me first explain the concept of :target: The pseudo selector matches when the fragment identifier (or hash, #content for instance) in the URL and the id of an HTML element are the same. If we have a URL like http://www.example.com/hallo.html#content and an element with the id="content" the selector #content:target { ... } would match.
You can´t really see the URL in this fiddel, but you will in another example. Her is the code of the fiddle:
HTML:
content
<div id="content">
Markup is poetry!
</div>
CSS:
#content {
border: 1px solid black;
padding: 20px;
}
#content:target {
background: lightblue;
}
The :target approach leads to this stripped down example to explain the page-navigation-idea: http://jsfiddle.net/Cxr73/1/ Again you can´t really see the URLs with the fragment identifier.
HTML:
div1
div2
div3
<div id="div2">
<div id="div3">
<div class="div1Inner">content div1</div>
<div class="div2Inner">content div2</div>
<div class="div3Inner">content div3</div>
</div>
</div>
CSS:
.div2Inner, .div3Inner,
#div2:target .div1Inner, #div3:target .div1Inner {
display: none;
}
#div2:target .div2Inner, #div3:target .div3Inner {
display: block;
}
Hide all divs that should not be displayed at first: .div2Inner, .div3Inner { display: none;}. So just <div class="div1Inner">content div1</div> is visible. Show the corresponding div when the fragment identifier is part of the URL: #div2:target .div2Inner, #div3:target .div3Inner {display: block;}. In the end you have to hide div1 when div2 or div3 are visible: #div2:target .div1Inner, #div3:target .div1Inner { display: none; }. Combine the first and the last CSS selector and you get to the CSS shown above.
Some recommendations on your markup:
As recommended by the HTML5 spec (4.2.5.5 Specifying the document's character encoding), add your charset declaration early to avoid a potential encoding-related security issue in IE. It should come in the first 1024 bytes.
The <center> element was deprecated because it defines the presentation of its contents. For this purposes we have CSS.
You are writing an HTML5 app, so throw in some more semantic markup, elements like: nav, header, section, footer, etc.
Here you have the final approach of my ideas, with your CSS plus the :target selectors (starts at line 600) and what I consider a clean markup:
Fiddle: http://jsfiddle.net/Cxr73/2/
To finally see the fragment identifier plus the :target in action and for test purposes another URL: DEMO ... this demo will disappear in a few days, but the fiddle will stay.
I think that pretty much matches all your needs. Have fun!

Pure CSS & JS drop down menu - onmouseover issue

I've written this code to create simple CSS and Javascript dropdown menu.
HTML:
<li>XYZ
<ul id="rankSubMenu" onmouseover="showRanksSubmenu()" onmouseout="hideRanksSubmenu()">
<li>AAA</li>
<li>BBB</li>
<li>CCC</li>
</ul>
</li>
CSS:
#rankSubMenu {
display: none;
position: absolute;
bottom: 10px;
left: 278px;
}
JS:
function showRanksSubmenu() {
document.getElementById('rankSubMenu').style.display = 'block';
}
function hideRanksSubmenu() {
document.getElementById('rankSubMenu').style.display = 'none';
}
Menu items have of course some height, background and other stuff to make them look like buttons. The problem is that, there is some empty space between this buttons (like a few pixels) and when user stops mouse cursor there, menu disappear (in fact menu always does that, unless you move your cursor real fast). I tried to define this whole area as div or try any other ideas that I thought about, but with no success. Any suggestions how can I solve this?
First off, welcome to the wonderful world of web development. Based on your use of inline styles, li as a top-level container, and attempted use of Javascript for a simple menu show/hide I can tell you're pretty new. No matter! Its a learning process, and web development is fun. :)
First, for what you want, you can do this via CSS only, and without the need for position:absolute in your menu items or anything crazy like that. Here is a working example of a cleaner menu display:
jsFiddle example
My recommendations for the learning process:
Get comfortable with external CSS sheets, use of inline styles is pretty ancient, and very difficult to maintain
Learn about the benefits of classes over IDs when styling; rarely (never?) do you need to use IDs for styling, and class is usually preferred because you can apply it to multiple elements
Get familiar with proper semantic markup; for example li should not be a top-level container, only the container of another ul if there is a sub list or something
Learn external JS event handlers; using inline onwhatever handlers in HTML is another pretty ancient method, and again makes maintenance very difficult
Best of luck!
CSS
.dropdown li{
float:left;
width: 240px;
position:relative;
}
.dropdown ol{
position:absolute;
left:-9999px; /* Hide off-screen when not needed (this is more accessible than
display:none;) */
}
.dropdown li:hover ol{ /* Display the dropdown on hover */
left:0; /* Bring back on-screen when needed */
}
HTML
<ul class="dropdown">
<li>
<a href="#" >Your Link</a>
<ol>
<li> Your Link 1 </li>
<li> Your Link 2 </li>
</ol>
</li></ul>
What else would u need for this? Is there any reason to use javascript to create this?
Take a look at this Fiddle. Perhaps it's what you're looking for.
it's only using HTML and CSS.
#rankSubMenu is probably 0px high, try to add some height, also you can do this js free by using :hover
My guess would be set your anchor tags to display block. If an anchor tag is not a block it will ignore a few css properties, width and height being the two main ones, so your click is just the text.
another possible reason is that the submenu coming in is partially covering the link (check your inspector to see what area it's covering).
if you set the height to that of the original item with overflow hidden and then on hover set height to auto
HTML
<nav class="navigation">
<ul>
<li>Menu</li>
<li>Home</li>
<li>About</li>
</ul>
</nav>
CSS
.navigation {
height: 20px;
overflow: hidden;
}
.navigation {
height: auto;
}
no javascript needed

Hide static (or hardcoded) text in HTML page

I have a HTML page containing some hardcoded/static text.
The text string does not have any class/id/name. It's just there.
How to hide it on page load?
P.S: I really hope this is not a repeat question. I have done my 'homework'.
You can hide an element that doesn't have any direct identifiers by using a CSS selector which examines structure. You didn't post your markup, so it's impossible to give an exact solution.
Example 1
HTML
<body>
<section>
<div>Div I want to hide</div>
</section>
</body>
CSS
SECTION > DIV { display: none; }
There are many permutations of this pattern and many selectors available.
See: CSS2 Selectors (very wide support) and CSS3 Selectors (supported in most newer browsers).
Example 2
Here's a more complex example:
HTML
<div id="foo">
<ul>
<li>Hide this item</li>
<li>Don't hide this</li>
<li>Don't hide this</li>
</ul>
</div>
CSS
/* hide the first child of any UL which is a direct descendant of #foo */
#foo > UL > LI:first-child { display: none; }
In CSS, display: none? That'd be the easiest way. Or you could go with javascript once the page has loaded.
If you're talking about doing it with javascript, you would have to do a window.onload and set the style.display = "none"; but that would require an id/class/some way to reference it (there are ways to reference it without them but it's a lot better style to just give it an id/class. The function would look something like this.
window.onload = function() {
document.getElementById("text").style.display = none;
};
where your string has an id of "text"
Although if you are determined to have the text just appear as none on startup, why not just set the style/css to originally to have a display of none?

Categories

Resources