0

I'm working on a wordpress site and trying to implement some javascript/jquery. The code I'm using is from Jfiddle: https://jsfiddle.net/cse_tushar/Dxtyu/141/ It seems to work perfectly there but when I copy this across to wordpress to place in my themes wp_footer hook it fails.

The code I've used in the following wrapped in a script tag:

jQuery(document).ready(function($) {
$(document).on("scroll", onScroll);

//smoothscroll
$('a[href^="#"]').on('click', function (e) {
    e.preventDefault();
    $(document).off("scroll");

    $('a').each(function () {
        $(this).removeClass('active');
    })
    $(this).addClass('active');

    var target = this.hash,
        menu = target;
    $target = $(target);
    $('html, body').stop().animate({
        'scrollTop': $target.offset().top+2
    }, 500, 'swing', function () {
        window.location.hash = target;
        $(document).on("scroll", onScroll);
    });
});
});
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#menu-center a').each(function () {
    var currLink = $(this);
    var refElement = $(currLink.attr("href"));
    if (refElement.position().top <= scrollPos && refElement.position().top + refElement.height() > scrollPos) {
        $('#menu-center ul li a').removeClass("active");
        currLink.addClass("active");
    }
    else{
        currLink.removeClass("active");
    }
});
}

Keep in mind I've just started using jQuery so theres a good chance I'm missing something obvious.

Error message read: Uncaught TypeError: $ is not a function at HTMLDocument.onScroll ((index):563) at HTMLDocument.dispatch (jquery.js?ver=1.12.4:3) at HTMLDocument.r.handle (jquery.js?ver=1.12.4:3)

Any help would be much appreciated.

  • 1
    What is the error given? You should be more descriptive. – Özgür Can Karagöz Apr 08 '18 at 09:25
  • Sorry, I get a `Uncaught TypeError: $ is not a function at HTMLDocument.onScroll ((index):563) at HTMLDocument.dispatch (jquery.js?ver=1.12.4:3) at HTMLDocument.r.handle (jquery.js?ver=1.12.4:3)` message. – Baskerville Apr 08 '18 at 22:46
  • I would recommend you to search the site first. The answer to the question you are looking for https://stackoverflow.com/questions/12343714/typeerror-is-not-a-function-when-calling-jquery-function given here. – Özgür Can Karagöz Apr 08 '18 at 23:03
  • Wrapped my code with `;(function($){ // your code })(jQuery);` seemed to fix it as outlined in the link you sent me. Thought I tried everything there, obviously missed one of the other answers. Thanks for your help. – Baskerville Apr 09 '18 at 04:02

0 Answers0