Cannot read property ‘substr’ of undefined in main.js

this code:

$(document).ready(function() {                     
$('a').click(function(){
    $('html, body').animate({
            scrollTop: $('[name="' + $.attr(this, 'href').substr(1) + '"]').offset().top //HERE THE ERROR
    }, 500);
    return false;
}); 
$("#slides").slidesjs({
        width: 940,
        height: 440,
       play: {
                 active: true,
                 auto: true,
                 interval: 9000,
                 swap: true
               }
      });            
});

gives me the error that i write in the title
Uncaught TypeError: Cannot read property ‘substr’ of undefined

Read More

This happen only when a try to do a particular action. This action is voting photo from a wordpress plugin: photo contest wordpress plugin.

So how can i stop that line of code if substr(1) is undefined?
I search problems like this on google but nothing works.
If i comment that line voting photo start to work but other function stops.

Related posts

Leave a Reply

1 comment

  1. As pointed out in the comments you’re using .attr incorrectly, but you also have stuff so chained together that when things go wrong it may be unclear exactly where things are messing up. Here’s your code cleaned up a bit to warn as soon as potential issue comes up (it’s probably overkill, but good for learning):

    $(document).ready(function() {
        $("a").click(function(){
            var $a = $(this),
                href = $a.attr("href");
    
            if (href && href.length > 1) {
                var sel = '[name="' + href.substr(1) + '"]',
                    $el = $(sel);
                if ($el) {
                    $("html, body").animate({
                        scrollTop: $el.offset().top
                    }, 500);
                } else {
                    console.warn("Could not find:", sel);
                }
            } else {
                console.warn("Clicked but no href found");
            }
            return false;
        });
    
        $("#slides").slidesjs({
            width: 940,
            height: 440,
            play: {
                active: true,
                auto: true,
                interval: 9000,
                swap: true
            }
        });
    });