How to add a scroll function with JS? - javascript

I am trying to add a scroll function to my landing page so that when the navi bar link is clicked, it smoothly scrolls to the section. instead of CSS, I should use JS, 'addEventListener','preventDefault' and ''scrollIntoView() to achieve this. I've been trying and trying for days, it just dosen't work, please help me!
here is my my CodePen link:
https://codepen.io/Qinisfighting/pen/bGYKEGe

I rewrote the code that you commented, but also changed a major part when you created the menu links.
const clickItems = document.querySelectorAll('.menu__link');
for (const clickItem of clickItems) {
clickItem.addEventListener("click", function(e){
e.preventDefault();
document.querySelector(e.currentTarget.dataset.href).scrollIntoView({behavior: "smooth"});
});
}
The main difference is that I changed your href attribute in the menu links into a data-href attribute, otherwise the native behavior would scroll down to your sections, just like any link would do.
navList += `<li id="${sectionName}"> <a class="navbar__menu menu__link" data-href="#${section.id}">${sectionName}</a></li>`;

You can search for the element and move directly
document.getElementById("myElement").scrollIntoView();
"behavior" Defines the transition animation. One of auto or smooth. Defaults to auto.
Post: How do I scroll to an element using JavaScript?

Related

jQuery smooth scrolling on a different webpage

I have managed to get the smooth scrolling working on a single page using the following code.
Note the HTML link is stored in a header.php and used across multiple pages below is a code snippet:
HTML Script:
<a class="item" href="index.php#contact">
<a name="contact"></a>
JS Script:
$('a[href="index.php#contact"]').click(function (e) { // user clicks on html link
e.preventDefault(); // prevent the default behaviour that occurs in the browser
var targetOffset = $('a[name="contact"]').offset().top; // define a variable to point at a particular section & offset from the top of browser
$('body').animate( // create animation
{ scrollTop: targetOffset }, 1000); // scrollTop property = target variable
});
Problem:
When I go to a different webpage and click the contact link it does not link back to the index.php#contact and scroll down to the contact anchor point.
Any assistance or advice is much appreciated I'm sure its a simple tweak in the code somewhere.
Check your href it's supposed to be: index.php/#contact

anchor href does not display properly

I am trying to navigate to another page section with anchor tag from current page /contact.html. The problem I am having here is that the result view do not correspond to the start of the container. Upon searching online, I suspect that it was because the web site components are dynamically loaded and do not have fixed height for the image slider.
Nonetheless, I did not find any solution to this problem yet. Hope someone can help me in this issue.
Note: The anchor tag work perfectly as it is if it is used in the index.html page itself.
For code reference and better illustrations, please refer to following link. This is exactly the problem I am facing.
Click here
Click here
Click here
As you said in comments, you have a fixed position on your header, so you need to calculate in JS your header height.
If you have jQuery:
$('a').on('click' function(){
var $link = $(location.href);
var position = $link.offset().top - $('#header').height()
$(window.animate({scrollTop: position},{duration: 500})
});
For onload with an anchor in the URL:
$(window).load(function() {
var $link = $(location.href);
if($link.length {
var position = $$link.offset().top - $('#header').height()
$(window.animate({scrollTop: position},{duration: 500})
}
});

Hiding Section/Slide Arrows on Pages - Fullpage.js

I'm working on a website using fullpage.js:
https://github.com/alvarotrigo/fullPage.js/
The first problem I had is that I need to hide the arrows once it falls into the last section and/or slide. ie. if you're on the far right slide, my hope is it will hide the right arrow. Top section, top arrow is hidden, etc.
I've tried quite a bit to make it work, I'm still learning javascript so forgive me if I'm way off, but I was hoping this was close:
function hideArrowUp() {
if(index == 1){
$('.arrowUp').hide();
}
else {
$('.arrowUp').show();
}
}
function hideArrowDown(anchorlink) {
if(index == 3){
$('.arrowDown').hide();
}
else {
$('.arrowDown').show();
}
}
And I was hope to prevent horizontal slides from repeating/rolling-over, not sure if that's an easy one.
Please and thanks!
Now You can to this with javascript options.
When u call the full page function on a div. Just set the option control arrow to false.
//call full page function with options.
$('#fullpage').fullpage({
anchors:['anchor-1','anchor-2'],
controlArrows: false,
});
Regards
Alex
Just use the plugin callbacks such as afterLoad or onLeave to remove the arrow by using javascript or by adding a class.
You can also use the class of type fp-viewing-xxxx added to your body element to apply one or another style.
Take a look at the demo page of fullpage.js. In that case you can inspect the DOM and see how the body gets the class fp-viewing-4thpage applied when reaching the last section. That's because it is using the anchor 4thpage as you can see in the URL (#4thpage).
Therefore you can do something like the following in your CSS stylesheet:
.fp-viewing-4thpage .myArrow{
display:none;
}
Remember the demo page and many others examples are available in the downloaded files.

jQuery: how to implement this roll-out effect?

I need some help to implement this roll over / out effect.
This is the screenshot: http://dl.dropbox.com/u/72686/roll-over-out.png
I have a menu. When I roll over the item "Products" the popup block appears below it, with a tree with all products.
<div id="menu">
<div id="product"> Roll over here </div>
...
</div>
<div id="popup">
<div> <a> link </a> </div>
<div> <a> link </a> </div>
<div> <a> link </a> </div>
...
</div>
This block has css:
#popup {
position:fixed
display:none
}
Now, it is clear how to implement roll over to show the block:
("#product").mouseover(function() {
$('#popup').css("display","block");
})
However how can I handle the rollout ? I have the following issues:
1) If I add roll-out to the menu item "#product", when I roll-out from it (to move to the popup with product trees), I make this last one to disappear (because I'm leaving the menu item).
2) If I add roll out functionality to the popup, I have issues with his children. i.e. If I move the mouse over a link of the tree, the popup disappear (because I'm leaving the parent #popup).
thanks
ps. I cannot use :hover (it is not supported by jquery version on Drupal CMS).
Firstly I think you will find that mouseenter and mouseleave are better events for this kind of thing. See the jQuery example in IE to understand why, not a huge problem but you may end up wit flickering otherwise.
However that will still not solve your problem. I would suggest use a setTimeout to close the menu, and then if your mouse enters the menu before the time out cancel the time out:
var t;
$("#product").mouseleave(function() {
t = setTimeOut(function(){$('#popup').hide();}, 100);
})
$("#popup").mouseenter(function() {
if(t)
{
clearTimeout(t);
t=null;
}});
This will prevent the popup from closing if you move from the product element to the pop up element. The clear timeout method prevents the timeout function from being executed.
Thorough Tutorial: Drop down menu
I have created similar solution, you can check it out here. See the demo here.
By the way, :hover isn't jQuery - it's CSS.
http://www.w3schools.com/cssref/sel_hover.asp

Prevent/stop auto anchor link from occurring

I need to prevent the automatic scroll-to behavior in the browser when using link.html#idX and <div id="idX"/>.
The problem I am trying to solve is where I'm trying to do a custom scroll-to functionality on page load by detecting the anchor in the url, but so far have not been able to prevent the automatic scrolling functionality (specifically in Firefox).
Any ideas? I have tried preventDefault() on the $(window).load() handler, which did not seem to work.
Let me reiterate this is for links that are not clicked within the page that scrolls; it is for links that scroll on page load. Think of clicking on a link from another website with an #anchor in the link. What prevents that autoscroll to the id?
Everyone understand I'm not looking for a workaround; I need to know if (and how) it's possible to prevent autoscrolling to #anchors on page load.
NOTE
This isn't really an answer to the question, just a simple race-condition-style kluge.
Use jQuery's scrollTo plugin to scroll back to the top of the page, then reanimate the scroll using something custom. If the browser/computer is quick enough, there's no "flash" on the page.
I feel dirty just suggesting this...
$(document).ready(function(){
// fix the url#id scrollto "effect" (that can't be
// aborted apparently in FF), by scrolling back
// to the top of the page.
$.scrollTo('body',0);
otherAnimateStuffHappensNow();
});
Credit goes to wombleton for pointing it out. Thanks!
This seems the only option I can see with ids:
$(document).ready(function() {
$.scrollTo('0px');
});
It doesn't automatically scroll to classes.
So if you identify your divs with unique classes you will lose a bit of speed with looking up elements but gain the behaviour you're after.
(Thanks, by the way, for pointing out the scroll-to-id feature! Never knew it existed.)
EDIT:
I know this is an old thread but i found something without the need to scroll. Run this first before any other scripts. It puts an anchor before the first element on the page that prevents the scroll because it is on top of the page.
function getAnchor(sUrl)
{
if( typeof sUrl == 'string' )
{
var i = sUrl.indexOf( '#' );
if( i >= 0 )
{ return sUrl.substr( i+1 ).replace(/ /g, ''); }
}
return '';
};
var s = getAnchor(window.location.href);
if( s.length > 0 )
{ $('<a name="'+s+'"/>').insertBefore($('body').first()); }
Cheers!
Erwin Haantjes
Scroll first to top (fast, no effects pls), and then call your scroll function. (I know its not so pretty)
or just use a prefix
This worked well for me:
1- put this on your css file
a[name] { position: absolute; top: 0px }
2- put this on your document.ready bind right before you start animating (if you're animating at all)
$("a[name]").css("position","relative");
Might need tweaking depending on your stylesheet/code but you get the idea.
Credit to: http://cssbeauty.com/skillshare/discussion/1882/disable-anchor-jump/

Categories

Resources