简体   繁体   中英

How to use an anchor link and scroll at the same time?

Here for some help again :)

I've got this site: sharemyplaylists.com

that uses this scrolling plugin to smoothly bring the user to an anchor when clicked, here is the code:

// Smooth anchor link script
$(document).ready(function() 
{
   $('a[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) 
         {
            var targetOffset = $target.offset().top;
            $('html,body')
               .animate({scrollTop: targetOffset}, 1000);
            return false;
         }
      }
   });
}); 

// open panel on click script
$(".btn-slide").click(function()
{
   $("#panel").slideToggle("slow");
   $(this).toggleClass("active"); return false;
});

Anyway, I also have a button "Submit your playlist" that opens the top panel to reveal a form in the sidebar and when I click this, it just opens the panel (meaning I am not brought up to the top anchor also). It's like the 2 bits of code are conflicting and only one script will work. Any ideas on how to Click the "Submit your playlist" in the sidebar, bring the user to the top header anchor and open the panel also in one click?

Cheers, Keith

you should insert scrolling into your function on button click, something like:

// open panel on click script
$(".btn-slide").click(function()                
{
  // here insert scrolling
  targetOffset = 0; // to scroll
  $('html,body').animate({scrollTop: targetOffset}, 1000);
  // toggle
  $("#panel").slideToggle("slow");
  $(this).toggleClass("active"); return false;
});

Maybe you should stop the event somehow. In prototype, I'd do something like this: $('.btn-slide').observe('click', function (e) { $('#panel').slide(); Event.stop(e); })

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM