Anchor/Pseudo-URL Hide/Show-CSS Issue - html

I trying to experiment with single page websites. However I have come to a point where I'm stuck.
I use Anchors and :target Pseudo-classes to get a website appearing as normal website. I do this by using div's that are switched to display: block/none as needed.
My cut down code to show the issue:
function showIndex() {
document.getElementById("Index").style.display = "block";
}
function hideIndex() {
document.getElementById("Index").style.display = "none";
}
#nav, #content {
padding: 10px;
margin: 0 0 20px 0;
}
.navButton {
float: left;
width: 50px;
background-color: blue;
padding: 5px;
margin: 0 10px 0 0;
color: white;
}
.contentBox {
float: clear;
width: 400px;
border: 1px solid blue;
padding: 5px;
}
#A, #B, #C {
display: none;
}
#A:target, #B:target, #C:target {
display: block;
}
<div id="nav">
Index</div>
<div class="navButton">Page A</div>
<div class="navButton">Page B</div>
<div class="navButton">Page C</div>
</div>
<div id="content">
<div id="Index" class="contentBox">Here is the Page: Index</div>
<div id="A" class="contentBox">Here is the Page: A</div>
<div id="B" class="contentBox">Here is the Page: B</div>
<div id="C" class="contentBox">Here is the Page: C</div>
</div>
Everything workign fine and as intended as long as the side is opned through index.html. However if I open the side through its anchor / pseudo-url like index.html#A, both divs (Index + A) will be shown instead of just A.
I'm aware why both are shown. If I hide Index by default, the user will get an empty page at start. I cant use .htaccess to redirect to the very same page like Redirect index.html index.html#Index and neither is declaring index.html#Index as startpage an option for different reasons.
Does anyone know a solution to hide Index Div if the page is opened through an anchor url?

One way to do accomplish this is with the hashchange event. Of course, with this, you will also want to remove the show and hide inline event listeners.
window.addEventListener("hashchange", function (e) {
let hash = location.hash.slice(1) || "Index";
document.querySelectorAll(".contentBox").forEach((el) => {
el.style.display = el.id === hash ? "block" : "none";
});
});
Just add that inside script tags. It will run once on load, and then every time the hash changes. If the hash is empty, it will show index. Otherwise, it will try and show whatever element has the id matching whatever the hash is. Only problem with this is that if the target is to "#V" and you don't have a .contentBox with the id of V, it won't show anything. You can work around this easily enough by testing if there are any visible .contentBox after the loop, but I'll leave that for you to figure out.
Edit: I would've thought this would catch page refreshes as well, but in the case that you want to cover every single base, you could do this:
function hideHash(){
let hash = location.hash.slice(1) || "Index";
document.querySelectorAll(".contentBox").forEach((el) => {
el.style.display = el.id === hash ? "block" : "none";
});
}
window.addEventListener('load',function(){
hideHash();
window.addEventListener("hashchange",hideHash);
});
This will add the event listener for the hashChange during the load event, after firing once during the load event. Doing it this way prevents it from accidentally firing twice on page load, which would probably cause some flickering. Note - if you notice flickering on page load, you can wrap the second event listener in a setTimeout function, because hashChange fires after load, and it's theoretically possible that it will still get called during load without introducing a delay.

Related

How to remove class when page loads but only once

I have a button that toggles active class on a div.
When the div has active class it is displayed and when active class is removed the div is hidden.
I want active class removed from the div when the page is loaded, but later when I click the button active class should be applied. The div should be hidden when the page loads.
I don't have access to HTML so it has to be done using jquery.
here is my code:
<button class="btn addclass">Toggle class</button>
<div class="block active">
</div>
my js:
$(document).ready(function(){
$(window).on('load', function(){
if($(".addclass .block").hasClass("active")){
$(this).removeClass("active");
}
});
});
$(document).ready(function(){
$(".addclass").click(function(){
$(".block").toggleClass("active");
});
});
CSS
.block{
display: none;
padding: 50px;
background-color: red;
}
.block.active{
display: block;
}
In this block of code:
$(document).ready(function(){
$(window).on('load', function(){
if ($(".addclass .block").hasClass("active")) {
$(this).removeClass("active");
}
});
this refers to the window so you can't use window here.
You also don't shouldn't nest window.load inside doc.ready (use one or the other). While doc.ready will fire even if the document is already ready, window load will only fire at the one time that it loads and that will be before doc.ready runs, so your code (probably) never runs.
Your code can be shortened to:
$(function() {
$(".addclass .block.active").removeClass("active");
});
Since jQuery specializes in controlling all things DOM it's a shade faster and less flashing if you listen for the "DOMContentLoaded" event on the document object. By that time all of the DOM is loaded and the scripts have been parsed. If you listen to the "load" event on the window object, then everything has been loaded, that includes all the stuff you didn't need to run jQuery.
BTW if you don't already know, it's important that all <script> elements be placed right before the closing </body> tag. Of course this may not be possible for you since you have to deal with 3rd party code at page load. See this article about what was just discussed.
/*
Once document is loaded
Remove .active from .block
*/
$(document).on('DOMContentLoaded', e => $('.block').removeClass('active'));
/* ALTERNATIVE
Once document is loaded
Hide .block
/
$(document).on('DOMContentLoaded', e => $('.block').hide());
*/
/*
When .toggle is clicked...
Toggle .block to hide/show
Toggle the text of .toggle to "SHOW/HIDE"
*/
$('.toggle').on('click', function(e) {
$(this).text($(this).text() === 'SHOW' ? 'HIDE' : 'SHOW');
/*
Toggle .active class on/off on .block
*/
$('.block').toggleClass('active');
/* ALTERNATIVE
Toggle .block show/hide slowly
/
$('.block').toggle('slow');
*/
});
body {
font: 5ch/1 Consolas;
text-align: center;
}
button {
font: inherit;
cursor: pointer;
}
.block {
display: none;
}
.active {
display: block;
}
<button class="btn toggle">SHOW</button>
<div class="block active">ACTIVE</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Scroll to a specific Element Using html

Is there a method in html which makes the webpage scroll to a specific Element using HTML !?
Yes you use this
<div id="google"></div>
But this does not create a smooth scroll just so you know.
You can also add in your CSS
html {
scroll-behavior: smooth;
}
You should mention whether you want it to smoothly scroll or simply jump to an element.
Jumping is easy & can be done just with HTML or Javascript. The simplest is to use anchor's. The limitation is that every element you want to scroll to has to have an id. A side effect is that #theID will be appended to the URL
Go to Title
<div>
<h1 id="scroll">Title</h1>
</div>
You can add CSS effects to the target when the link is clicked with the CSS :target selector.
With some basic JS you can do more, namely the method scrollIntoView(). Your elements don't need an id, though it is still easier, e.g.
function onLinkClick() {
document.getElementsByTagName('h2')[3].scrollIntoView();
// will scroll to 4th h3 element
}
Finally, if you need smooth scrolling, you should have a look at JS Smooth Scroll or this snippet for jQuery. (NB: there are probably many more).
<!-- HTML -->
<div id="google"></div>
/*CSS*/
html { scroll-behavior: smooth; }
Additionally, you can add html { scroll-behavior: smooth; } to your CSS to create a smooth scroll.
Year 2020. Now we have element.scrollIntoView() method to scroll to specific element.
HTML
<div id="my_element">
</div>
JS
var my_element = document.getElementById("my_element");
my_element.scrollIntoView({
behavior: "smooth",
block: "start",
inline: "nearest"
});
Good thing is we can initiate this from any onclick/event and need not be limited to tag.
If you use Jquery you can add this to your javascript:
$('.smooth-goto').on('click', function() {
$('html, body').animate({scrollTop: $(this.hash).offset().top - 50}, 1000);
return false;
});
Also, don't forget to add this class to your a tag too like this:
Text
Here is a pure HTML and CSS method :)
html {
scroll-behavior: smooth;
/*Adds smooth scrolling instead of snapping to element*/
}
#element {
height: 100px;
width: 100%;
background-color: red;
scroll-margin-block-start: 110px;
/*Adds margin to the top of the viewport*/
scroll-margin-block-end: 110pxx;
/*Adds margin to the bottom of the viewport*/
}
#otherElement {
padding-top: 500px;
width: 100%;
}
Link
<div id="otherElement">Content</a>
<div id="element">
Where you want to scroll
</div>
<div id="otherElement">Content</a>
<nav>
1
2
3
</nav>
<section id="section1">1</section>
<section id="section2" class="fifty">2</section>
<section id="section3">3</section>
<style>
* {padding: 0; margin: 0;}
nav {
background: black;
position: fixed;
}
a {
color: #fff;
display: inline-block;
padding: 0 1em;
height: 50px;
}
section {
background: red;
height: 100vh;
text-align: center;
font-size: 5em;
}
html {
scroll-behavior: smooth;
}
#section1{
background-color:green;
}
#section3{
background-color:yellow;
}
</style>
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script type="text/javascript" >
$(document).on('click', 'a[href^="#"]', function (event) {
event.preventDefault();
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
});
</script>
I got it working by doing this, consider that top-page is the element that you want to scroll to:
document.getElementById("top-page").scrollTo({ behavior: "smooth", top: 0 });
Yes, you may use an anchor by specifying the id attribute of an element and then linking to it with a hash.
For example (taken from the W3 specification):
You may read more about this in Section Two.
...later in the document
<H2 id="section2">Section Two</H2>
...later in the document
<P>Please refer to Section Two above
for more details.
By using an href attribute inside an anchor tag you can scroll the page to a specific element using a # in front of the elements id name.
Also, here is some jQuery/JS that will accomplish putting variables into a div.
<html>
<body>
Click here to scroll to the myContent section.
<div id="myContent">
...
</div>
<script>
var myClassName = "foo";
$(function() {
$("#myContent").addClass(myClassName);
});
</script>
</body>
Should you want to resort to using a plug-in, malihu-custom-scrollbar-plugin, could do the job. It performs an actual scroll, not just a jump. You can even specify the speed/momentum of scroll. It also lets you set up a menu (list of links to scroll to), which have their CSS changed based on whether the anchors-to-scroll-to are in viewport, and other useful features.
There are demo on the author's site and let our company site serve as a real-world example too.
The above answers are good and correct. However, the code may not give the expected results. Allow me to add something to explain why this is very important.
It is true that adding the scroll-behavior: smooth to the html element allows smooth scrolling for the whole page. However not all web browsers support smooth scrolling using HTML.
So if you want to create a website accessible to all user, regardless of their web browsers, it is highly recommended to use JavaScript or a JavaScript library such as jQuery, to create a solution that will work for all browsers.
Otherwise, some users may not enjoy the smooth scrolling of your website / platform.
I can give a simpler example on how it can be applicable.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
// Add smooth scrolling to all links
$("a").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes to scroll to the specified area
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = hash;
});
} // End if
});
});
</script>
<style>
#section1 {
height: 600px;
background-color: pink;
}
#section2 {
height: 600px;
background-color: yellow;
}
</style>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<h1>Smooth Scroll</h1>
<div class="main" id="section1">
<h2>Section 1</h2>
<p>Click on the link to see the "smooth" scrolling effect.</p>
Click Me to Smooth Scroll to Section 2 Below
<p>Note: Remove the scroll-behavior property to remove smooth scrolling.</p>
</div>
<div class="main" id="section2">
<h2>Section 2</h2>
Click Me to Smooth Scroll to Section 1 Above
</div>
</body>
</html>

How do you make a div "tabbable"?

I have buttons that are div elements and I want to make them so that it is possible for the user to press the tab key on their keyboard and move between them. I've tried wrapping their text in anchor tags but it doesn't seem to work.
Does anyone have a solution?
Add tabindex attributes to your div elements.
Example:
<div tabindex="1">First</div>
<div tabindex="2">Second</div>
Per steveax's comment, if you don't want the tab order to deviate from where the element is in the page, set the tabindex to 0:
<div tabindex="0">First</div>
<div tabindex="0">Second</div>
for those interested, in addition to the accepted answer, you can add the following jquery to make the div style change when you tab to it, and also handle Enter and Space to trigger a click (then your click handler will do the rest)
$(document).on('focus', '.button',function(){
$(this).css('border','1px dotted black')
});
$(document).on('keyup', '.button',function(e){
if(e.which==13 || e.which==32)
$(this).click()
});
I'm sure someone has made this into a jq plugin $().makeTabStop
Add the tabindex="0"attribute to each div you want tabbable. Then use CSS pseudo classes :hover and :focus, for example to signify to the app user that the div is in focus and clickable, for example. Use JavaScript to handle the click.
var doc = document;
var providers = doc.getElementsByClassName("provider");
for (var i = 0; i < providers.length; i++) {
providers[i].onclick = function() {
console.log(this.innerHTML);
};
}
.provider {
flex: 0 1 auto;
align-self: auto;
width: 256px;
height: 48px;
margin-top: 12px;
margin-right: 12px;
text-align: center;
line-height: 48px;
text-transform: uppercase;
background-size: contain;
background-repeat: no-repeat;
background-position: 10%;
background-color: gray;
}
.provider:hover{
cursor: pointer;
}
.provider:focus{
-webkit-box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
-moz-box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
box-shadow: 0px 2px 8px 2px rgba(0,0,0,0.4);
}
<h4>Click in this area first then press tab</h4>
<div id="email" class="provider" tabindex="0">email</div>
<div id="facebook" class="provider" tabindex="0">facebook</div>
<div id="github" class="provider" tabindex="0">github</div>
<div id="google" class="provider" tabindex="0">google</div>
<div id="twitter" class="provider" tabindex="0">twitter</div>
Make elements tabbable and clickable with key press using jquery
Assumptions
All elements that are of a non-tabbable, non-clickable type and should be clickable have an onclick attribute (this could be changed to a class or other attribute)
All elements are of the same type; I will use divs.
You're using jquery
Sample html:
...
<div onclick="clicked(this)">Button 1</div>
<div onclick="clicked(this)">Button 2</div>
<div onclick="clicked(this)">Button 3</div>
...
Jquery code:
This is the code that will run when the page has loaded. It needs to run on your HTML page.
$(()=>{
// make divs with an onclick attribute tabbable/clickable
$('div[onclick]')
.attr('tabindex', '0') // Add tab indexes
.keypress((evt)=>{
var key = evt.key;
evt.preventDefault(); // Ensure all default keypress
// actions are not used
if (key === ' ' || key === 'Enter') { // Only send click events for Space
// or Enter keys
evt.currentTarget.click(); // Run the click event for element
}
});
});
You can find a working example here.
For anyone that shows up on this page for the opposite intention, as in to make a div tag NOT tabbable: https://github.com/WICG/inert is a good way.

Dynamic Div or assigning multiple functions to a Div in CSS/HTML

I'm relatively new to Web dev. The question is generic, but I'll pose specific user-cases.
Use-case 1:
I have a div element on a web page. When the page loads the first time, this div runs a small 5 sec animation. What I wish to do is, when this animation ends, I want the same div to contain some other element - it could be an image, a link, another animation etc.
That is, one container - the div - hosting multiple elements on a time-scale. First 5 secs animation , followed by an image or a link.
What Javascript methods will allow me to do so?
Use-case 2:
Again, I have a div element in a page. Now this div element is like a tabbed browser - you click on a different tab to view a different web page. Similarly, I wish to make this a "tabbed" div. As in, when the user hovers the mouse on tab 1, the div would show a video, when hovered over tab 2, it would show another video in the same div - that is, replacing the old video. The tabs can be considered as a fancy looking link.
Or, in the first place, is there an alternative to 'div' to do the things mentioned above?
Thanks,
SMK.
Solution for use case 2 -
This is a slightly lengthy solution but its extremely flexible and can be scaled up to any number of tabs very easily
We will divide the solution into 3 parts - The CSS, HTML and JQuery.
Lets take a look at the CSS part first
<style>
#tab_holder {
width: 350px; !important
}
#tab_holder .tabs {
float: left;
height: 20px;
padding: 5px;
border: 1px solid #eee;
border-bottom: none;
width: 50px;
cursor: pointer;
border-radius: 5px 5px 0 0;
}
#tab_holder .tabs:hover {
background-color: #eee;
}
#tab_holder #content_holder {
width: 400px; !important
margin: 0 0 0 0;
border: 1px solid #000;
padding: 10px;
float: left;
border-radius: 0 5px 5px 5px;
}
.content {
visibility: hidden;
}
</style>
Let us now take a look at the HTML part of this solution
<div id="tab_holder">
<div id="tab1" class="tabs">Video1</div>
<div id="tab2" class="tabs">Video2</div>
<div id="tab3" class="tabs">Video3</div>
<div id="content_holder">
<div id="main_content">Select a tab to see the video..</div>
</div>
</div>
<!-- These are divs in which you put your actual content.
They are always hidden -->
<div id="content1" class="content">
<iframe width="200" height="200" src="http://www.youtube.com/embed/4Z6YUGGlwtA?rel=0" frameborder="0" allowfullscreen></iframe>
< /div>
<div id="content2" class="content">
<iframe width="200" height="200" src="http://www.youtube.com/embed/s13dLaTIHSg?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
<div id="content3" class="content">
<iframe width="200" height="200" src="http://www.youtube.com/embed/I1qHVVbYG8Y?rel=0" frameborder="0" allowfullscreen></iframe>
</div>
You can see that each tab is represented by a div which is using the "tabs" class from the CSS section. If you need to add a new tab, all you have to do is add a new div and give is a new id. For example to add a forth tab, you can say -
<div id="tab4" class="tabs">Video4</div>
It is as simple as that.
Now the thing I like about this approach is that you can place the content to be displayed also in div's, rather that nesting it under jquery. In this case we use the div's with the id content1 content2 content3
This gives you the flexibility to expand as you enter content into the div and use normal markup without getting confused and at ease.
These div's are not visible as we have set their visibility to hidden is CSS.
If you add a new tab div you must also add a new content div.
Now we move onto the JQuery part -
$(document).ready(function (){
/* Add the listeners. */
$("#tab1").mouseover(function (){
switch_content('content1')
});
$("#tab2").mouseover(function (){
switch_content('content2')
});
$("#tab3").mouseover(function (){
switch_content('content3')
});
});
function switch_content(name){
$("#main_content").fadeOut('fast',function (){
$("#main_content").html($("#"+name).html());
$("#main_content").fadeIn('fast');
});
}
The above JQuery function is extremely straight forward. Each tab is attached a action listener which is fired by a mousover event. So if you add another tab with the id=tab4 and its respective content div with the id=content4 then all you have to add in the jQuery is:
$("#tab4").mouseover(function (){
switch_content('content4')
});
So it becomes very easy to expand the code.
You can find a working demo of this on my website demo section
Tips -
Avoid using hover because it creates an annoying user experience due to accidental hovers and it is hard for mobile platforms to emulate this event. Most of them fall back to click. So I suggest use the click event instead.
If you must use, make use of the HTML video tag and pause the video using JS if the user hovers on another tab. This will render a better user experience.
Here is an example for use-case 1.
In your html you need to include the 5 second animation, i persume this is a gif? Although it can be any content. For the sake of this example i will show it as a div.
The html i have used:
<div id="example">
<div id="somecontent"> </div>
<div id="morecontent"> </div>
</div>
The CSS:
#example
{
width:500px;
height:500px;
background-color:#f00;
padding:10px;
}
#somecontent
{
width:200px;
height:200px;
background-color:#fff;
}
#morecontent
{
width:200px;
display:none;
height:200px;
background-color:#000;
}
and the javascript(using jQuery):
setTimeout(function() {
$("#somecontent").fadeOut("slow", function() {
$("#morecontent").fadeIn("slow");
});
}, 5000);​
Have a look at this jsfiddle for it in action - http://jsfiddle.net/fntWZ/
For use case 2 it will be more complicated. Try having a look for some different plugins that could help with this
answer for use-case:1
css :
<style>
#myDiv {
height:0;
width:0;
position:absolute;
border:1px solid red;
}
</style>
script :
$(document).ready(function(){
$("#myDiv").animate({width:"100px", height:"100px"},5000, function(){
var image = new Image();
image.src = "dropdownContainerBottomMiddle.png"; //your image src goes here
$("#myDiv").append(image);
//you can append more content by using setTimeout function
setTimeout(function(){
var anc = "stackoverflow";
$("#myDiv").append(anc);
}, 1000);
});
});
html:
<div id="myDiv"></div>

Fixed position navbar obscures anchors [duplicate]

This question already has answers here:
Fixed page header overlaps in-page anchors
(38 answers)
Closed 7 years ago.
I am trying to clean up the way my anchors work. I have a header that is fixed to the top of the page, so when you link to an anchor elsewhere in the page, the page jumps so the anchor is at the top of the page, leaving the content behind the fixed header (I hope that makes sense). I need a way to offset the anchor by the 25px from the height of the header. I would prefer HTML or CSS, but Javascript would be acceptable as well.
You could just use CSS without any javascript.
Give your anchor a class:
<a class="anchor" id="top"></a>
You can then position the anchor an offset higher or lower than where it actually appears on the page, by making it a block element and relatively positioning it. -250px will position the anchor up 250px
a.anchor {
display: block;
position: relative;
top: -250px;
visibility: hidden;
}
I found this solution:
<a name="myanchor">
<h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</a>
This doesn't create any gap in the content and anchor links works really nice.
I was looking for a solution to this as well. In my case, it was pretty easy.
I have a list menu with all the links:
<ul>
<li>one</li>
<li>two</li>
<li>three</li>
<li>four</li>
</ul>
And below that the headings where it should go to.
<h3>one</h3>
<p>text here</p>
<h3>two</h3>
<p>text here</p>
<h3>three</h3>
<p>text here</p>
<h3>four</h3>
<p>text here</p>
Now because I have a fixed menu at the top of my page I can't just make it go to my tag because that would be behind the menu.
Instead, I put a span tag inside my tag with the proper id.
<h3><span id="one"></span>one</h3>
Now use 2 lines of CSS to position them properly.
h3{ position:relative; }
h3 span{ position:absolute; top:-200px;}
Change the top value to match the height of your fixed header (or more).
Now I assume this would work with other elements as well.
FWIW this worked for me:
[id]::before {
content: '';
display: block;
height: 75px;
margin-top: -75px;
visibility: hidden;
}
As this is a concern of presentation, a pure CSS solution would be ideal. However, this question was posed in 2012, and although relative positioning / negative margin solutions have been suggested, these approaches seem rather hacky, create potential flow issues, and cannot respond dynamically to changes in the DOM / viewport.
With that in mind I believe that using JavaScript is still (February 2017) the best approach. Below is a vanilla-JS solution which will respond both to anchor clicks and resolve the page hash on load (See JSFiddle). Modify the .getFixedOffset() method if dynamic calculations are required. If you're using jQuery, here's a modified solution with better event delegation and smooth scrolling.
(function(document, history, location) {
var HISTORY_SUPPORT = !!(history && history.pushState);
var anchorScrolls = {
ANCHOR_REGEX: /^#[^ ]+$/,
OFFSET_HEIGHT_PX: 50,
/**
* Establish events, and fix initial scroll position if a hash is provided.
*/
init: function() {
this.scrollToCurrent();
window.addEventListener('hashchange', this.scrollToCurrent.bind(this));
document.body.addEventListener('click', this.delegateAnchors.bind(this));
},
/**
* Return the offset amount to deduct from the normal scroll position.
* Modify as appropriate to allow for dynamic calculations
*/
getFixedOffset: function() {
return this.OFFSET_HEIGHT_PX;
},
/**
* If the provided href is an anchor which resolves to an element on the
* page, scroll to it.
* #param {String} href
* #return {Boolean} - Was the href an anchor.
*/
scrollIfAnchor: function(href, pushToHistory) {
var match, rect, anchorOffset;
if(!this.ANCHOR_REGEX.test(href)) {
return false;
}
match = document.getElementById(href.slice(1));
if(match) {
rect = match.getBoundingClientRect();
anchorOffset = window.pageYOffset + rect.top - this.getFixedOffset();
window.scrollTo(window.pageXOffset, anchorOffset);
// Add the state to history as-per normal anchor links
if(HISTORY_SUPPORT && pushToHistory) {
history.pushState({}, document.title, location.pathname + href);
}
}
return !!match;
},
/**
* Attempt to scroll to the current location's hash.
*/
scrollToCurrent: function() {
this.scrollIfAnchor(window.location.hash);
},
/**
* If the click event's target was an anchor, fix the scroll position.
*/
delegateAnchors: function(e) {
var elem = e.target;
if(
elem.nodeName === 'A' &&
this.scrollIfAnchor(elem.getAttribute('href'), true)
) {
e.preventDefault();
}
}
};
window.addEventListener(
'DOMContentLoaded', anchorScrolls.init.bind(anchorScrolls)
);
})(window.document, window.history, window.location);
Pure css solution inspired by Alexander Savin:
a[name] {
padding-top: 40px;
margin-top: -40px;
display: inline-block; /* required for webkit browsers */
}
Optionally you may want to add the following if the target is still off the screen:
vertical-align: top;
My solution combines the target and before selectors for our CMS. Other techniques don't account for text in the anchor. Adjust the height and the negative margin to the offset you need...
:target::before {
content: '';
display: block;
height: 180px;
margin-top: -180px;
}
This takes many elements from previous answers and combines into a tiny (194 bytes minified) anonymous jQuery function. Adjust fixedElementHeight for the height of your menu or blocking element.
(function($, window) {
var adjustAnchor = function() {
var $anchor = $(':target'),
fixedElementHeight = 100;
if ($anchor.length > 0) {
$('html, body')
.stop()
.animate({
scrollTop: $anchor.offset().top - fixedElementHeight
}, 200);
}
};
$(window).on('hashchange load', function() {
adjustAnchor();
});
})(jQuery, window);
If you don't like the animation, replace
$('html, body')
.stop()
.animate({
scrollTop: $anchor.offset().top - fixedElementHeight
}, 200);
with:
window.scrollTo(0, $anchor.offset().top - fixedElementHeight);
Uglified version:
!function(o,n){var t=function(){var n=o(":target"),t=100;n.length>0&&o("html, body").stop().animate({scrollTop:n.offset().top-t},200)};o(n).on("hashchange load",function(){t()})}(jQuery,window);
For modern browsers, just add the CSS3 :target selector to the page. This will apply to all the anchors automatically.
:target {
display: block;
position: relative;
top: -100px;
visibility: hidden;
}
You can do it without js and without altering html. It´s css-only.
a[id]::before {
content: '';
display: block;
height: 50px;
margin: -30px 0 0;
}
That will append a pseudo-element before every a-tag with an id. Adjust values to match the height of your header.
I had been facing a similar issue, unfortunately after implementing all the solutions above, I came to the following conclusion.
My inner elements had a fragile CSS structure and implementing a position relative / absolute play, was completely breaking the page design.
CSS is not my strong suit.
I wrote this simple scrolling js, that accounts for the offset caused due to the header and relocated the div about 125 pixels below. Please use it as you see fit.
The HTML
<div id="#anchor"></div> <!-- #anchor here is the anchor tag which is on your URL -->
The JavaScript
$(function() {
$('a[href*=#]:not([href=#])').click(function() {
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'')
&& location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 125 //offsets for fixed header
}, 1000);
return false;
}
}
});
//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var target = $('#'+location.href.split("#")[1]);
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - 125 //offset height of header here too.
}, 1000);
return false;
}
}
});
See a live implementation here.
For the same issue, I used an easy solution : put a padding-top of 40px on each anchor.
As #moeffju suggests, this can be achieved with CSS. The issue I ran into (which I'm surprised I haven't seen discussed) is the trick of overlapping previous elements with padding or a transparent border prevents hover and click actions at the bottom of those sections because the following one comes higher in the z-order.
The best fix I found was to place section content in a div that is at z-index: 1:
// Apply to elements that serve as anchors
.offset-anchor {
border-top: 75px solid transparent;
margin: -75px 0 0;
-webkit-background-clip: padding-box;
-moz-background-clip: padding;
background-clip: padding-box;
}
// Because offset-anchor causes sections to overlap the bottom of previous ones,
// we need to put content higher so links aren't blocked by the transparent border.
.container {
position: relative;
z-index: 1;
}
Solutions with changing position property are not always possible (it can destroy layout) therefore I suggest this:
HTML:
<a id="top">Anchor</a>
CSS:
#top {
margin-top: -250px;
padding-top: 250px;
}
Use this:
<a id="top"> </a>
to minimize overlapping, and set font-size to 1px. Empty anchor will not work in some browsers.
Borrowing some of the code from an answer given at this link (no author is specified), you can include a nice smooth-scroll effect to the anchor, while making it stop at -60px above the anchor, fitting nicely underneath the fixed bootstrap navigation bar (requires jQuery):
$(".dropdown-menu a[href^='#']").on('click', function(e) {
// prevent default anchor click behavior
e.preventDefault();
// animate
$('html, body').animate({
scrollTop: $(this.hash).offset().top - 60
}, 300, function(){
});
});
The above methods don't work very well if your anchor is a table element or within a table (row or cell).
I had to use javascript and bind to the window hashchange event to work around this (demo):
function moveUnderNav() {
var $el, h = window.location.hash;
if (h) {
$el = $(h);
if ($el.length && $el.closest('table').length) {
$('body').scrollTop( $el.closest('table, tr').position().top - 26 );
}
}
}
$(window)
.load(function () {
moveUnderNav();
})
.on('hashchange', function () {
moveUnderNav();
});
* Note: The hashchange event is not available in all browsers.
You can achieve this without an ID using the a[name]:not([href]) css selector. This simply looks for links with a name and no href e.g. <a name="anc1"></a>
An example rule might be:
a[name]:not([href]){
display: block;
position: relative;
top: -100px;
visibility: hidden;
}
Instead of having a fixed-position navbar which is underlapped by the rest of the content of the page (with the whole page body being scrollable), consider instead having a non-scrollable body with a static navbar and then having the page content in an absolutely-positioned scrollable div below.
That is, have HTML like this...
<div class="static-navbar">NAVBAR</div>
<div class="scrollable-content">
<p>Bla bla bla</p>
<p>Yadda yadda yadda</p>
<p>Mary had a little lamb</p>
<h2 id="stuff-i-want-to-link-to">Stuff</h2>
<p>More nonsense</p>
</div>
... and CSS like this:
.static-navbar {
height: 100px;
}
.scrollable-content {
position: absolute;
top: 100px;
bottom: 0;
overflow-y: scroll;
width: 100%;
}
There is one significant downside to this approach, however, which is that while an element from the page header is focused, the user will not be able to scroll the page using the keyboard (e.g. via the up and down arrows or the Page Up and Page Down keys).
Here's a JSFiddle demonstrating this in action.
This was inspired by the answer by Shouvik - same concept as his, only the size of the fixed header isn't hard coded. As long as your fixed header is in the first header node, this should "just work"
/*jslint browser: true, plusplus: true, regexp: true */
function anchorScroll(fragment) {
"use strict";
var amount, ttarget;
amount = $('header').height();
ttarget = $('#' + fragment);
$('html,body').animate({ scrollTop: ttarget.offset().top - amount }, 250);
return false;
}
function outsideToHash() {
"use strict";
var fragment;
if (window.location.hash) {
fragment = window.location.hash.substring(1);
anchorScroll(fragment);
}
}
function insideToHash(nnode) {
"use strict";
var fragment;
fragment = $(nnode).attr('href').substring(1);
anchorScroll(fragment);
}
$(document).ready(function () {
"use strict";
$("a[href^='#']").bind('click', function () {insideToHash(this); });
outsideToHash();
});
I'm facing this problem in a TYPO3 website, where all "Content Elements" are wrapped with something like:
<div id="c1234" class="contentElement">...</div>
and i changed the rendering so it renders like this:
<div id="c1234" class="anchor"></div>
<div class="contentElement">...</div>
And this CSS:
.anchor{
position: relative;
top: -50px;
}
The fixed topbar being 40px high, now the anchors work again and start 10px under the topbar.
Only drawback of this technique is you can no longer use :target.
Adding to Ziav's answer (with thanks to Alexander Savin), I need to be using the old-school <a name="...">...</a> as we're using <div id="...">...</div> for another purpose in our code. I had some display issues using display: inline-block -- the first line of every <p> element was turning out to be slightly right-indented (on both Webkit and Firefox browsers). I ended up trying other display values and display: table-caption works perfectly for me.
.anchor {
padding-top: 60px;
margin-top: -60px;
display: table-caption;
}
I added 40px-height .vspace element holding the anchor before each of my h1 elements.
<div class="vspace" id="gherkin"></div>
<div class="page-header">
<h1>Gherkin</h1>
</div>
In the CSS:
.vspace { height: 40px;}
It's working great and the space is not chocking.
how about hidden span tags with linkable IDs that provide the height of the navbar:
#head1 {
padding-top: 60px;
height: 0px;
visibility: hidden;
}
<span class="head1">somecontent</span>
<h5 id="headline1">This Headline is not obscured</h5>
heres the fiddle: http://jsfiddle.net/N6f2f/7
You can also add an anchor with follow attr:
(text-indent:-99999px;)
visibility: hidden;
position:absolute;
top:-80px;
and give the parent container a position relative.
Works perfect for me.
A further twist to the excellent answer from #Jan is to incorporate this into the #uberbar fixed header, which uses jQuery (or MooTools). (http://davidwalsh.name/persistent-header-opacity)
I've tweaked the code so the the top of the content is always below not under the fixed header and also added the anchors from #Jan again making sure that the anchors are always positioned below the fixed header.
The CSS:
#uberbar {
border-bottom:1px solid #0000cc;
position:fixed;
top:0;
left:0;
z-index:2000;
width:100%;
}
a.anchor {
display: block;
position: relative;
visibility: hidden;
}
The jQuery (including tweaks to both the #uberbar and the anchor approaches:
<script type="text/javascript">
$(document).ready(function() {
(function() {
//settings
var fadeSpeed = 200, fadeTo = 0.85, topDistance = 30;
var topbarME = function() { $('#uberbar').fadeTo(fadeSpeed,1); }, topbarML = function() { $('#uberbar').fadeTo(fadeSpeed,fadeTo); };
var inside = false;
//do
$(window).scroll(function() {
position = $(window).scrollTop();
if(position > topDistance && !inside) {
//add events
topbarML();
$('#uberbar').bind('mouseenter',topbarME);
$('#uberbar').bind('mouseleave',topbarML);
inside = true;
}
else if (position < topDistance){
topbarME();
$('#uberbar').unbind('mouseenter',topbarME);
$('#uberbar').unbind('mouseleave',topbarML);
inside = false;
}
});
$('#content').css({'margin-top': $('#uberbar').outerHeight(true)});
$('a.anchor').css({'top': - $('#uberbar').outerHeight(true)});
})();
});
</script>
And finally the HTML:
<div id="uberbar">
<!--CONTENT OF FIXED HEADER-->
</div>
....
<div id="content">
<!--MAIN CONTENT-->
....
<a class="anchor" id="anchor1"></a>
....
<a class="anchor" id="anchor2"></a>
....
</div>
Maybe this is useful to somebody who likes the #uberbar fading dixed header!
#AlexanderSavin's solution works great in WebKit browsers for me.
I additionally had to use :target pseudo-class which applies style to the selected anchor to adjust padding in FF, Opera & IE9:
a:target {
padding-top: 40px
}
Note that this style is not for Chrome / Safari so you'll probably have to use css-hacks, conditional comments etc.
Also I'd like to notice that Alexander's solution works due to the fact that targeted element is inline. If you don't want link you could simply change display property:
<div id="myanchor" style="display: inline">
<h1 style="padding-top: 40px; margin-top: -40px;">My anchor</h1>
</div>
Here's the solution that we use on our site. Adjust the headerHeight variable to whatever your header height is. Add the js-scroll class to the anchor that should scroll on click.
// SCROLL ON CLICK
// --------------------------------------------------------------------------
$('.js-scroll').click(function(){
var headerHeight = 60;
$('html, body').animate({
scrollTop: $( $.attr(this, 'href') ).offset().top - headerHeight
}, 500);
return false;
});
I ran into this same issue and ended up handling the click events manually, like:
$('#mynav a').click(() ->
$('html, body').animate({
scrollTop: $($(this).attr('href')).offset().top - 40
}, 200
return false
)
Scroll animation optional, of course.