Add padding-top to scroll when using href="#id" - javascript

I have an anchor tag as follows:
A Guide
It navigates to a section that has the id 'map_4D85448A3D4C4180A02BD6FC387ABC45'. The jumptosection function is as follows:
function jumptosection(id) {
var target = document.getElementById(id);
if(document.all){
document.documentElement.scrollTop = target.offsetTop;
}else{
var top = 0;
do {
top += target.offsetTop || 0;
target = target.offsetParent;
} while(target);
document.body.scrollTop = top ;
}
//$('#article').css.paddingTop = '55px';
return false;
But even if I write nothing in this function, the behaviour is still the same. The problem is that I have a header strip of 92px that hides some part of the section when I click on the given anchor. How do I make it scroll to the given section while adding some pixels to escape the header?

While the chosen answer serves the purpose, we now have explicit CSS property for this, called scroll-margin.
Basically, you avoid any trickery by adding unnecessary elements - this margin is just calculated when you navigate via anchor tag (or if you have set up native css scroll snapping - https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Scroll_Snap/Basic_concepts).
Using this with CSS variables is really useful. Here's an example if you have a fixed / sticky header:
/* Set the header variable */
--h-header: 50px;
/* Set the scroll margin top on all anchor elements by using .anchor class */
/* Note: I'm setting plus 2.5em so the element has some breathing room on the top */
.anchor {
scroll-margin-top: calc(var(--h-header) + 2.5em);
}
MDN Docs: https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-margin
CSS-Tricks guide: https://css-tricks.com/almanac/properties/s/scroll-margin/

It is possible. I would do it without javascript, so it works for all. Even no changes on you JS are needed.
You just need to create an empty element above the element you want to scroll to. The CSS does the magic. It creates a hidden box in the height of you offset:
HTML:
<span class="anchor" id="map_4D85448A3D4C4180A02BD6FC387ABC45"></span>
<h1>Element to scroll to</h1>
CSS:
.anchor {
display: block;
height: 92px;
margin-top: -92px;
visibility: hidden;
}
See a working demo here:
https://jsfiddle.net/eczxm1rs/1/

Related

How to move HTML elements when a page is scrolled?

How to make an HTML element that is initially 'fixed' then when we scroll the web page down or more specifically through the element, the element will move to the side or wherever we specify. And of course when we scroll the web page back up and pass the element, it will return to normal.
Please help if there is, I ask for an article or explanation of what to use and an example of the source code.
You can use sticky for that: https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_sticky_element
div.sticky {
position: -webkit-sticky; /* Safari */
position: sticky;
top: 0;
}
I'm using jQuery for something similar on my app. The following code will add the class of 'scroll-active' to the 'nav' when scrolled 10px, and removes it when there is nothing scrolled.
$(function () {
$(window).on('scroll', function () {
if ( $(window).scrollTop() > 10 ) {
$('nav').addClass('scroll-active');
} else {
$('nav').removeClass('scroll-active',);
}
});
});
I think you can use this and add the necessary css to it on your added class to have it on the right side.
You'll probably need javascript for that, this might work for you if you don't want to use jQuery.
<div id="container">
some content
</div>
and some javascript to define add a class:
window.addEventListener('scroll', function(e) {
container = document.getElementById('container');
// The 0 could be a larger threshold if you want to move it after scrolling a bit
container.classList.toggle('scrolling', window.scrollY > 0);
});
and then define your CSS:
#container {
/* style when not scrolling */
}
#container.scrolling {
/* style when scrolling */
position: fixed;
}
here is a working jsfiddle: https://jsfiddle.net/96xvotpc/2/

Navbar hiding text after clicking on anchor link

I've recently been using Twitter Bootstrap, and I've been loving it.
I've created a navbar that is fixed to the top, and inside it is my logo, a header, a few links, and a dropdown that says "Jump to:". Upon clicking on the dropdown, a menu comes down with four links to a section within the page. All of the links work.
My problem is that because the header of each section is now placed at the top of my page, my fixed navbar blocks it. Is there anyway I can stop this from happening? A bit of jQuery or something?
This is my website: fishyfishy2014.gweb.io. Thanks in advance.
I think you are asking about an anchor jump, which will place the matching anchor to the top of the viewport and "under" the fixed nav. I had a similar issue and used this code:
/* fixing anchor jumps */
var nav_height = 77; // pixels
$(window).bind('hashchange', function(e){
if($(location.hash).hasClass('anchor')){
scrollBy(0, nav_height);
}
return false;
});
$(document).ready(function(){
if($(location.hash).hasClass('anchor')){
$('html,body').animate({
scrollTop: $(location.hash).offset().top - nav_height - 10
}, 10 );
}
});
You just have to add the anchor CSS class to any element, you want be able to jump to.
You need to set this:
body { padding-top: 70px; }
This is coming from the Bootstrap docs itself
Body padding required The fixed navbar will overlay your other
content, unless you add padding to the top of the . Try out your
own values or use our snippet below. Tip: By default, the navbar is
50px high.
You can check here
The following works without any JS:
a:not([href]):before {
display: block;
content: "";
height: 60px;
margin: -60px 0 0;
}
a:not([href]) assumes that your anchors don't have a href attribute. Change both occurrences of 60px to a value of your choice.
Actually, 2ndkauboy's solution does work. In short:
get rid of the 'px' in nav_height variable (...as you said)
use the anchor css class (...as 2ndkauboy said) but DONOT use it on the <a> tag but on the <div>, as follows:
click here
... other code here ...
<div id="jump_here" class="anchor">
... content ...
</div>
Hope it helps.
In CSS, there is also the scroll-margin-top property that sets the element's scroll margin to the top side.
You need to apply to anchored element a class, for exemple .anchor
After that, you can apply this :
.anchor {
scroll-margin-top: 77px;
}

Making a sticky header stick to the top

I have managed to make a dropdown for a website I am designing and I'm a bit stuck on the sticky header part..
My header has the sticky effect however when i scroll down the header does not stick to the top of the page. It always maintains a margin of 80px from the top as i mentioned in the CSS.
How can i make the header stick to the TOP when i scroll and when i scroll back to the top of the page it should retain its original position. Hope i have made myself clear.
Just pasting my CSS as the HTML is too lengthy in the fiddle.
#nav, #nav ul {
list-style: none outside none;
margin: 0;
padding: 0;
z-index:9998;
position:relative;
}
Check this fiddle for a DEMO I have created.
EDIT: Just to be clear. I want the top:80px to be there initially. I only want the header to stick to the top while scrolling. EXAMPLE
Here you go.
WORKING DEMO
Changes in CSS:
#nav {
position:fixed;
top:-40px;
}
You have some conflicting styles you need to get rid of:
http://jsfiddle.net/5GqYh/4/
Firstly, you had top inline your header, so I set it to 0.
I also adjust the top margin on your menu, that was also pushing it down.
Try these:
Remove this from ur css to make the header stick to the top.
#nav {
..
margin:40px auto;
..
}
2.css style for header - position:relative will do instead of position:fixed.
3.Put the content div inside another div and create a scrollbar only for that div. In that way, your header will always stick to the top.
Create a .sticky class on your CSS that makes the element's position fixed, then you can easily detect if the user scrolled enough to make it stick to the top, at which point you add the .sticky class to the element. Of course when the user scrolls all the way back you should remove the class. Example:
function stick() {
var stickyNavTop = $('.nav').offset().top;
var scrollTop = $(window).scrollTop();
if(stickyNavTop > scrollTop) {
$('.nav').addClass('sticky');
} else {
$('.nav').removeClass('sticky');
}
}
$(window).scroll(function() {
stick();
});

Hide iframe scrollbar but allow scrolling [duplicate]

I want to hide any scrollbars from my div elements and my whole body, but still let the user scroll with the mouse wheel or arrow keys. How can this be achieved with raw JavaScript or jQuery? Any ideas?
Like the previous answers, you would use overflow:hidden to disable the scrollbars on the body/div.
Then you'd bind the mousewheel event to a function that would change the scrollTop of the div to emulate scrolling.
For arrow keys, you would bind the keydown event to recognize an arrow key, and then change scrollTop and scrollLeft of the div as appropriate to emulate scrolling.
(Note: you use keydown instead of keypress since IE doesn't recognize keypress for arrow keys.)
Edit: I couldn't get FF/Chrome to recognize keydown on a div, but it works in IE8. Depending on what you needed this for, you can set a keydown listener on the document to scroll the div. (Check out the keyCode reference as an example.)
For example, scrolling with the mouse wheel (using jQuery and a mousewheel plugin):
<div id="example" style="width:300px;height:200px;overflow:hidden">
insert enough text to overflow div here
</div>
<script>
$("#example").bind("mousewheel",function(ev, delta) {
var scrollTop = $(this).scrollTop();
$(this).scrollTop(scrollTop-Math.round(delta));
});
</script>
(This is a quick mockup, you'd have to adjust the numbers since for me, this scrolls a bit slowly.)
keyCode reference
mousewheel plugin
keydown, keypress # quirksmode
Update 12/19/2012:
The updated location of the mousewheel plugin is at: https://github.com/brandonaaron/jquery-mousewheel
What about a purely CSS solution?
Solution 1 (cross browser but more hacky)
#div {
position: fixed;
right: -20px;
left: 20px;
background-color: black;
color: white;
height: 5em;
overflow-y: scroll;
overflow-x: hidden;
}
<html>
<body>
<div id="div">
Scrolling div with hidden scrollbars!<br/>
On overflow, this div will scroll with the mousewheel but scrollbars won't be visible.<br/>
Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>
</div>
</body>
</html>
Solution 2 (uses experimental features, may not support some browsers)
Just add the nobars class to any element you want to hide the scrollbars on.
.nobars {
/* Firefox: https://developer.mozilla.org/en-US/docs/Web/CSS/scrollbar-width */
scrollbar-width: none;
/* IE: https://msdn.microsoft.com/en-us/library/hh771902(v=vs.85).aspx */
-ms-overflow-style: none;
}
.nobars::-webkit-scrollbar {
/* Chrome/Edge/Opera/Safari: https://css-tricks.com/custom-scrollbars-in-webkit/ */
display: none;
}
Solution 3 (cross browser javascript)
Perfect Scrollbar doesn't require jQuery (although it can utilise jQuery if installed) and has a demo available here. The components can be styled with css such as in the following example:
.ps__rail-y {
display: none !important;
}
Here is a complete example including the implementation of Perfect Scrollbar:
<link rel="stylesheet" href="css/perfect-scrollbar.css">
<style>
#container {
position: relative; /* can be absolute or fixed if required */
height: 200px; /* any value will do */
overflow: auto;
}
.ps__rail-y {
display: none !important;
}
</style>
<script src='dist/perfect-scrollbar.min.js'></script>
<div id="container">
Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>Scrollable<br>
</div>
<script>
// on dom ready...
var container = document.getElementById("container");
var ps = new PerfectScrollbar(container);
//ps.update(container);
//ps.destroy(container);
</script>
You dont have to use jquery or js to make this. Its more performant with simple webkit.
Just add the code below to your css file.
::-webkit-scrollbar {
display: none;
}
Caution !
This will disable all the scrollbar so be sure to put it in a specific class or id if you just want one to be hidden.
I much prefer SamGoody's answer provided to a duplicate of this question. It leaves native scrolling effects intact, instead of trying to manually re-implement for a few particular input devices:
A better solution is to set the target div to overflow:scroll, and wrap it inside a second element that is 8px narrower, who's overflow:hidden.
See the original comment for a fleshed-out example. You may want to use JavaScript to determine the actual size of scrollbars rather than assuming they are always 8px wide as his example does.
To get this working for me, I used this CSS:
html { overflow-y: hidden; }
But I had problems using $(this).scrollTop(), so I bound to my #id, but adjusted the scrollTop of window. Also, my smooth scrolling mouse would fire lots of 1 or -1 deltas, so I multiplied that by 20.
$("#example").bind("mousewheel", function (ev, delta) {
var scrollTop = $(window).scrollTop();
$(window).scrollTop(scrollTop - Math.round(delta * 20));
});
As Baldráni said above
::-webkit-scrollbar { display: none; }
Or you can do
::-webkit-scrollbar{ width: 0px; }
(posted for other people that stumble on this from google search!)
Well, perhaps not the most intuitive in my opinion, but I can imagine you being able to make it a decent experience, give this a try.
overflow:hidden;
make sure the parent object has a height and width, and displays as block

How do I make a div follow me as I scroll down the page?

The user enters the site.
At this point, the div is in the middle of the page.
As he scrolls down the page, the div first begins to move upward, but once it hits the top, it stays there.
As he scrolls further down the page, the div stays near the top, always visible to the user.
As he scrolls up the page all the way to the top, the div once again stays back in position where it was originally.
You can hook the scroll event on the window object. When processing the event, look at the vertical scroll position of the window/document (see this answer on SO for how to do that). Use absolute positioning for your div and update its top as coordinate as necessary.
FWIW, I would be very careful doing this. Usually when a user scrolls, it's because they want to look at different content than what's on the page. Personally, I hate boxes that follow me around on web pages. :-) But that doesn't mean there isn't a good reason for doing this on occasion.
Very basic example (live copy):
// Make sure this is in a script tag at the end of the body,
// just prior to the closing </body> tag.
function getScrollTop() {
if (typeof window.pageYOffset !== "undefined" ) {
// Most browsers
return window.pageYOffset;
}
var d = document.documentElement;
if (typeof d.clientHeight !== "undefined") {
// IE in standards mode
return d.scrollTop;
}
// IE in quirks mode
return document.body.scrollTop;
}
window.onscroll = function() {
var box = document.getElementById("box");
var scroll = getScrollTop();
if (scroll <= 28) {
box.style.top = "30px";
} else {
box.style.top = (scroll + 2) + "px";
}
};
#box {
/* Position absolutely, 30px down from the top */
position: absolute;
top: 30px;
/* In my case I'm centering it in the window; do what you like */
margin-left: -100px;
left: 50%;
width: 200px;
/* These are just for my example */
height: 1.25em;
border: 1px solid #bbb;
text-align: center;
}
<div id='box'>I'm the box</div>
<div style="height: 1000px"></div>
(In my case, I'm always keeping it 2 pixels below the top, but if you don't want that you can adjust the numbers accordingly.)
As you can see other people provided ready scripts, but if you want to make one your self (waste of time) [or you may want to learn].. here is a good point to start:
var hscroll = (document.all ? document.scrollLeft : window.pageXOffset);
var vscroll = (document.all ? document.scrollTop : window.pageYOffset);
This solution is a lot simpler and might work just as good for some. Position: Fixed or Position: Sticky could do the job.
<div class="col" style="position:fixed; top: 250px; left: 50%">
<p>this box follows me while scrolling down</p>
</div>
http://jsfiddle.net/25rgq/
This is an old implementation of your desired functionality, which I've used. It's one of the first scripts I wrote, so JS & jQuery knowing people will most likely vomit. I wrote it mainly due all the examples I found online were centered on moving the DIV rather than setting it to fixed, and incrementally adding to the top-margin of the box resulted in really choppy movement.
Basicly it changes to fixed as the specified element is a custom set margin from the top of the browser window, and stops moving down once it hits a custom offset before our footer (we wanted to constrain the followbox to not move past our sidebar space).
Hope it is of any use, and if a plugin to handle this nowadays exists, you would probably be better of using it.

Categories

Resources