简体   繁体   中英

Getting jQuery error on click -> Uncaught TypeError: Cannot read property 'top' of undefined

I am not an jQuery expert and I would like to know if I am doing something wrong that generate errors in jQuery when clicking on 2 icons I have in a simple table.

In the specific here when I click on the pdf icon or on the envelope icon I see in console that an error is generate (the number increase every time I click on one of the 2 icons). Plus, the links I set for the icons are not working anymore.

On the right as you can see I have an animation. This is simply script code that I deactivated to see if was that the problem but it didn't worked.

Unfortunately I am using a plugin for the CMS and I cannot change it's code.

This is the error

(index):62 Uncaught TypeError: Cannot read property 'top' of undefined
    at HTMLTableElement.<anonymous> ((index):62)
    at HTMLTableElement.dispatch (jquery-1.12.4.js:5226)
    at HTMLTableElement.elemData.handle (jquery-1.12.4.js:4878)

This is the code

//your current click function
$('.scroll').on('click',function(e){
    e.preventDefault();
    $('html,body').animate({
        scrollTop:$($(this).attr('href')).offset().top + 'px'
    },1000,'swing');
});

You could try adding a class to the links for those two icons, eg I add class="clickable":

<a class="clickable" href="https://kirchmatt-breitenbach.ch/wp-content/uploads/2018/10/C16-0.2.pdf" target="_blank"><img src="https://kirchmatt-breitenbach.ch/wp-content/uploads/2018/10/pdf.png" height="20" width="auto"></a>

Then add this to your javascript:

$(".clickable, .clickable img").on('click', function(e){
   e.stopPropagation();
}

So that the scroll javascript code doesn't run when you click on these two links.

Perhaps change the script:

//your current click function
$('.scroll').on('click',function(e){
    e.preventDefault();
    var href = $(this).attr('href'), $ele = $(href);
    if ($ele && $ele.offset()) {
      var top = $ele.offset().top + 'px'
      $('html,body').animate({
        scrollTop:top
      },1000,'swing');
    }   
});

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