phlipinmi
phlipinmi

Reputation: 63

jQuery TypeError .offset is undefined

have been trying to resolve this issue for many hours now and just cant figure it out.

The environment is WordPress I am using a smooth scroll function that will smooth scroll when I select a link on one page to a location on another page.

the error I am getting is...

TypeError: $(...).offset(...) is undefined

the offending line of code is...

  scrollTop: $(elem).offset().top - headerHeight

My entire function is

jQuery(document).ready(function($) {

var headerHeight = $('#header-wrap').height(); //When the header position is fixed

$('a').click(function(){
    var hashEle = $(this).attr('href').split('#');
    if (hashEle.length > 1) {
        if (hashEle[1] == 'top') {
            $('body, html').animate({
                scrollTop: 0
            },800);
        } else {
        jQuery('body, html').animate({
            scrollTop: $('#'+ hashEle[1]).offset().top - headerHeight
        },800);
        }
    };
})
// find element from url
hashname = window.location.hash.replace('#', '');
elem = $('#' + hashname);
if(hashname.length > 1) {
    if(hashname == 'top') {
    $('body, html').animate({
            scrollTop: 0
        },500); 
    } else {
     $('body, html').animate({
            scrollTop: $(elem).offset().top - headerHeight
        },800);
 }
};

 });

I am going crazy here, the code works fine but it is creating a conflict with WooCommerce and I would just like it not to throw an error. Can someone tell me why this is causing trouble, sorry for the newbi question!

Upvotes: 2

Views: 13635

Answers (1)

Giancarlo PSK
Giancarlo PSK

Reputation: 231

I may have found out the problem:

  • the script works fine
  • the hash is wrong!

You said you have ##location in your URL string. If you use:

window.location.hash

It won't return anything. The right hash should be #location, which is different from ##location.

If you hardcode the hash in your URL and try again you'll see it works. If it doesn't work, then you have some script acting before which causes it (but I don't think so if you're just following a link, which should be worng)

To try it out, then change ##location with #top (or any thing according to your page elements)

Upvotes: 1

Related Questions