Make Named Anchor Bookmarks Appear Always at Top of the Screen When Clicked

Make named anchor bookmarks appear always at top of the screen when clicked

Here is what i did:

  1. the user scroll down the page.
    nothing unusual happens (there is no change to your page).

  2. the user click/use your anchor.
    the code creates some empty space after #content, so it can place the desired part on top of the screen.

  3. the user scroll the page up to the first div inside #content (could be any point you like) or hit the back button to go to the top of the page.
    the empty space disappears (your page is back to normal).

Test online here: http://jsfiddle.net/RASG/z3q3s/

Or save this code as an HTML file to test it on your pc:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>

<head>
<script src="http://code.jquery.com/jquery.min.js" type="text/javascript"></script>
<script>
$(document).ready(function() {
function isScrolledIntoView(elem){
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();

var elemTop = $(elem).offset().top;
var elemBottom = elemTop + $(elem).height();

return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}

var elem_that_hides_dummydiv = $('#content div:first');
var elem_that_shows_dummydiv = $('#content div:last');
$(window).scroll(function() {
if (isScrolledIntoView(elem_that_hides_dummydiv)) { $('#dummydiv').hide() }
});
$('#gonnaclickhere').click(function() {
$('#dummydiv').css({'height':(elem_that_shows_dummydiv.offset().top)+'px'}).show()
})
});
</script>
</head>

<body>

<ul class="sub_navi">
<li><a href="#sheds_housing">Sheds & Housing</a></li>
<li><a href="#feed_fodder">Feed & Fodder</a></li>
<li id="gonnaclickhere"><a href="#med_vac">Medication & Vaccination</a></li>
</ul>

<div id="content">

<div id="content_pic">
<img src="images/cattle/cattle_main.jpg" width="400" height="300" alt="Cattle Main" title="Cattle Main" />
</div>

<p>Pak United Food Services Ltd., (PUFS) has earned a creditable name and become a major player in the animal husbandry market by building upon Pakistan's large livestock population. Introducing the concept of corporate cattle farming on scientific lines, the conglomerate uses a livestock development policy consisting of innovative strategies and action plans with the intention of bringing about a radical change in the current livestock production system. The cattle farms are established on rich and fertile acres of land and consist of an impressive and mixed herd of cows/buffalos and sheep/goats.</p>
<p>A hybrid meat breed is developed by crossing the local indigenous breeds which are predominately draught/milch animals with high meat yielding animals from other parts of the world. A herd management system is incorporated to improve record keeping and obtain information for bench marking decisions. The farms employ a state of the art feedlot design involving the integration of the standard components into a fully functional operating system. This consists of housing, feeding, watering, health-care and cattle effluent & manure management systems, making them well known across the country.</p>

<div id="sheds_housing">
<h1>sheds & housing</h1>
<img src="images/cattle/sheds_housing.png" width="150" height="150" alt="Sheds & Housing" title="Sheds & Housing" />
<p>The housing for the animals utilizes a proper lay out for the farm buildings while keeping in view the environment, climate and wind direction. Sheds, pens and paddocks are constructed according to different categories and sex groups besides other infrastructure & allied facilities. All buildings are made airy for the protection of the animals from extreme temperatures and strong winds. Adequate supply of water for drinking and cleaning is made necessary with strict maintenance of hygienic conditions. Ample sunlight and natural ventilation is assured to assist in the reduction of moisture and bacteria, offering a healthier, cleaner & drier environment while also reducing the risk of disease and mortality in the livestock.</p>
</div>

<div id="feed_fodder">
<h1>feed & fodder</h1>
<img src="images/cattle/feed_fodder.png" width="150" height="150" alt="Feed & Fodder" title="Feed & Fodder" />
<p>The farms are equipped with in-house feed formulation capabilities which produce feed of constant quality and are palatable, nutritious and free from contamination. Feed supplies are made available according to different feed formulae while keeping in view the nutrient value and energy levels. Daily requirements are worked out for each category and class to achieve improved growth & overall health. A restricted feeding regime is employed that is balanced &amp; concentrated, containing minerals & vitamins, leading to an improved feed/gain ratio. Fodder & wheat/rice straws are purchased/contracted from the nearest markets, while treating it with ammonia or urea to improve the quality and gain a marked effect on cattle weight during the fattening period.</p>
</div>

<div id="med_vac">
<div id="med_vac_title">
<h1>medication & vaccination</h1>
</div>
<img src="images/cattle/med_vac.png" width="150" height="150" alt="Medication & Vaccination" title="Medication & Vaccination" />
<p>Regular vaccination of the whole herd against contagious and infectious diseases are carried out as a prophylactic measure in order to make sure that the animals are free of diseases of digestive, respiratory, urinary, gynecological and obstetrics by a designated veterinarian. A proactive health plan in employed to improve the health, welfare and productivity of the animals. A pre-weaning vaccination program is used with correct, effective and proper vaccines, dewormers, antibiotics and other medications to prime the immune systems of the animals. Furthermore post-weaning vaccination program is used to boost the immune system of the animals and increase the passive protection against common endemic livestock diseases.</p>
</div>

</div>

<div id='dummydiv' style="bottom: 0; width: 100%;"></div>

</body>

</html>

Tested with FF13 and IE9.

HTML: Making a link lead to the anchor centered in the middle of the page

There is no straight way of doing this in pure html\css. It is possible though using js, by getting the element's top location and setting the page's top position to that element's position minus half of the page's height.

How to prevent a click on a '#' link from jumping to top of page?

In jQuery, when you handle the click event, return false to stop the link from responding the usual way prevent the default action, which is to visit the href attribute, from taking place (per PoweRoy's comment and Erik's answer):

$('a.someclass').click(function(e)
{
// Special stuff to do when this link is clicked...

// Cancel the default action
e.preventDefault();
});

Make anchor link go some pixels above where it's linked to

window.addEventListener("hashchange", function () {
window.scrollTo(window.scrollX, window.scrollY - 100);
});

This will allow the browser to do the work of jumping to the anchor for us and then we will use that position to offset from.

EDIT 1:

As was pointed out by @erb, this only works if you are on the page while the hash is changed. Entering the page with a #something already in the URL does not work with the above code. Here is another version to handle that:

// The function actually applying the offset
function offsetAnchor() {
if(location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}

// This will capture hash changes while on the page
window.addEventListener("hashchange", offsetAnchor);

// This is here so that when you enter the page with a hash,
// it can provide the offset in that case too. Having a timeout
// seems necessary to allow the browser to jump to the anchor first.
window.setTimeout(offsetAnchor, 1); // The delay of 1 is arbitrary and may not always work right (although it did in my testing).

NOTE:
To use jQuery, you could just replace window.addEventListener with $(window).on in the examples. Thanks @Neon.

EDIT 2:

As pointed out by a few, the above will fail if you click on the same anchor link two or more times in a row because there is no hashchange event to force the offset.

This solution is very slightly modified version of the suggestion from @Mave and uses jQuery selectors for simplicity

// The function actually applying the offset
function offsetAnchor() {
if (location.hash.length !== 0) {
window.scrollTo(window.scrollX, window.scrollY - 100);
}
}

// Captures click events of all <a> elements with href starting with #
$(document).on('click', 'a[href^="#"]', function(event) {
// Click events are captured before hashchanges. Timeout
// causes offsetAnchor to be called after the page jump.
window.setTimeout(function() {
offsetAnchor();
}, 0);
});

// Set the offset when entering page with hash present in the url
window.setTimeout(offsetAnchor, 0);

JSFiddle for this example is here

href=# Going to Top of Page - Prevent?

In your event handler, add e.preventDefault(); (assuming e is the name of the variable holding the event):

$('.service').click(function(e) {
e.preventDefault();
});

Anchor links to start below the header which is fixed at the top

Ive got an even better solution to this problem.

• Firstly in the css a class can be created (call it whatever you want)

.anchor{
display:block;
height:63px; /* this is the height of your header */
margin-top:-63px; /* this is again negative value of the height of your header */
visibility:hidden;
}

• In the HTML just before your actual div section starts, for example mine is #landingcontainer you should add a span tag with the class of anchor (which we made above) and an id of whatever you want. for me I did this :

<span class="anchor" id="landing"></span>

Then the actual link will not now be linked to your actual div id of the section you want to take them to, but rather the id of the span tag must be given in the link.

<a href="#landing">HOME</a>

AND THERE YOU HAVE IT!

what we are doing here in essence is making the browser stop where the span starts which is exactly the height of the header, which then makes the viewer non the wiser ;)

Fixed page header overlaps in-page anchors

I had the same problem.
I solved it by adding a class to the anchor element with the topbar height as the padding-top value.

<h1><a class="anchor" name="barlink">Bar</a></h1>

I used this CSS:

.anchor { padding-top: 90px; }


Related Topics



Leave a reply



Submit