Tag and Name Attribute Animated Scrolling

I did this http://jsfiddle.net/thilakar/WsxJy/3/ using the tag and name attributes of the binding.

but I need to do this using jquery as shown below. http://www.jibevisuals.com/

when you click on the menu page "about us" slowly moves up. I need such a job.

Any suggestion

Thanks in advance.

+6
source share
4 answers

Description

You can do this using jQuery.offset() and jQuery.animate() .

Check out the jsFiddle demo .

Example

 function scrollToAnchor(aid){ var aTag = $("a[name='"+ aid +"']"); $('html,body').animate({scrollTop: aTag.offset().top},'slow'); } scrollToAnchor('id3'); 

Additional Information

+14
source

You can use jQuery Animation :

  var $root = $('html, body'); $('a').click(function() { if ($.attr(this, 'href').indexOf("#")!=-1&&$.attr(this, 'href')!="#") { $root.animate({ scrollTop: $( $.attr(this, 'href') ).offset().top }, 500); return false; } }); 

So, if you use the following link:

<a href="#home"></a>

and put the anchors in the right place:

<a id="home"></a>

smoothly scrolls to the anchor tag.

This free jQuery menu plugin works with this method: PageScroll jQuery Menu Plugin

+1
source

Snake Eyes answer is the most dynamic since you don't need to encode every tag in js. All the client needs to do is use an HTML solution, better for managing CMS.

This little piece of code is all you need (well, of course, jQuery too)

  $ (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
         }, 1000);
         return false;
       }
     }
   });
 });
    

Even if you have a stickymenu solution at the top of the page, pay attention to replacing #main_menu with the identifier or class of your menu:

  $ (function () {
     $ ('a [href * = #]: not ([href = #])'). click (function () {
         if (location.pathname.replace (/ ^ \ //, '') == this.pathname.replace (/ ^ \ //, '') && location.hostname == this.hostname) {
             var height_menu = $ ("# main_menu"). css ("height");
             height_menu = parseInt (height_menu, 10);

             var target = $ (this.hash);
             target = target.length?  target: $ ('[name =' + this.hash.slice (1) + ']');
             if (target.length) {
                 $ ('html, body'). animate ({
                 scrollTop: target.offset (). top - height_menu
                 }, 1000);
                 return false;
             }
         }
     });
 });

0
source

Source: https://habr.com/ru/post/905075/


All Articles