TEN Design TEN Design - 3 months ago 13
jQuery Question

jQuery fire function after another script is complete

I have a typing animation plugin that takes several second to run. At the very and a button is displayed. I also have a function for smooth scrolling to an anchor link and stripping the anchor from the URL. I load they typing script on document ready, and the scrolling function on window load. The problem I am having is that the scrolling function is not being fired when clicking on the anchor link in the typing plugin. I also tried calling the scrolling function imediately after the typing plugin. My code currently looks like this.

function anchorLinks() {
$('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 -1
}, 500);
return false;
}
}
});
};


$(window).load(function(){
anchorLinks();
});


and then...

$(document).ready(function(){
$('#msg').typeIt({
speed: 50,
breakLines: false,
autoStart: false,
cursor: false,
startDelay: 2000
})
.tiType('Hi!')
.tiPause(1500)
.tiDelete()
.tiType('I\'m Sandra Willford, and welcome to TENDesign.')
.tiPause(1500)
.tiDelete()
.tiType('Looking for a designer that has bright ideas for your brand?')
.tiPause(1500)
.tiDelete()
.tiType('Well congratulations, you\'ve landed in the right spot :)')
.tiPause(1500)
.tiDelete()
.tiType('I specialize in fresh and innovative digital, website & branding designs.')
.tiPause(1500)
.tiDelete()
.tiType('Are you ready to take your brand to the next level?')
.tiPause(1500)
.tiDelete()
.tiType('<a href="#start">OMG, Yes I am!...Show me more.</a>');
anchorLinks();
});


suggestions would be greatly appreciated!

Answer

I think you need something like this. Not tested:

$(document).on('click', 'a[href*=#]:not([href=#])', function (e) {
    e.preventDefault(); //<!-- use this instead return false. 
    //Return false is triggering preventDefault and stopPropagation also.
    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 - 1
            }, 500);
        }
    }
});
  • You no need to call the function from your code, since, I removed it.

  • Use $(document).on() for elements what loaded dynamically.

  • Do not use document.ready inside the function.

  • Do not attach event handler inside of the function if it is really not necessearry. Instead of this, use off() where is need.