I am trying to implement a smooth scroll when the user clicks on a link to an anchor in my Joomla site. The anchor link works fine, but the user is brought to the anchor instantly. I don't believe the javascript is working correctly, but I do not get any sort of error in my console on Google Chrome.

This is the exact working javascript I am using: http://codepen.io/anon/pen/RNBMXZ

It works fine there, but when I try to put it in my Joomla site, it does not. I currently have the script at the end of the article with the anchor, but I also tried to load it in a file in the header.

Like I said, I do not see any sort of errors, so I'm not sure where to go from here.

EDIT: Here is the output of console.log(target) when the anchor link is clicked. enter image description here

up vote 0 down vote accepted

It sounds like you may not have wrapped document ready around your code, so try copying and pasting the following:

jQuery(document).ready(function($){   
    $('a[href^="#"]').on('click', function(e) {

        var target = $( $(this).attr('href') );

        if( target.length ) {
            e.preventDefault();
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 1000);
        }   
    });  
});

The problem

The problem being is that the child span element for your menu item has an onclick function, like so:

<a href="#test">
    <span onclick="window.document.location.href="#test">test</span>
</a>

So the standard href="#test" is not triggered.

I don't know how your template works, but somehow, you need to remove the following from the span element:

onclick="window.document.location.href="#test"
  • No change when implementing document ready. That's actually something I had tried. – Intrepid Mar 4 '15 at 19:12
  • start using console.log() to see if anything is returning null – Lodder Mar 4 '15 at 19:25
  • I've never used console log before. This does not seem to be working for me:jQuery(document).ready(function($){ $('a[href^="#"]').on('click', function(e) { console.log ( var target = $( $(this).attr('href') ); if( target.length ) { e.preventDefault(); $('html, body').animate({ scrollTop: target.offset().top }, 1000); } ); }); }); – Intrepid Mar 4 '15 at 19:37
  • I added a console.log after my click function and when I click my anchor link, I see my console log. So it does appear that it is getting that far. – Intrepid Mar 4 '15 at 19:40
  • You only need to console log the variable like so: console.log (target); – Lodder Mar 4 '15 at 20:42

Your Answer

 

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.