Search code examples
javascriptjquerycastingsubstr

fix needed regarding Uncaught TypeError: Cannot read property 'substr' of undefined


The script below currently used to extract URL and to perform an image swap on mouseover. However, I'm currently getting uncaught type error:

cannot read property 'substr' of undefined

The code is:

<script>
jQuery(document).ready(function(){
    jQuery('.hover_box_wrapper').mouseenter(function(){
        var img_src = jQuery(this).parent().parent().parent().find('.hover2 img').attr('src');
        var img_src_s= img_src.substring(0,img_src.lastIndexOf("?"));
        var img_href = jQuery(this).parent().attr('href');
        var img_src_set = jQuery(this).parent().parent().parent().find('.hover2 img').attr('srcset');
        var src = jQuery('.center123').find('img').attr('src');
        var res = src.split(" ");
        var src_first = res[0];
         src_first = src_first.substring(0,src_first.lastIndexOf("?")); 

        jQuery('.center123').find('img').attr('src',img_src_s);
        jQuery('.center123').find('img').attr('srcset',src_first);

        //var img_html = jQuery('.center123').find('.vc_single_image-wrapper').html();
        //jQuery('.center123').find('.vc_single_image-wrapper').html('');
        jQuery('.center123').find('.vc_single_image-wrapper').html('<a href="'+ img_href + '"><img src="'+ img_src_s+'" srcset="'+ src_first +'" /></a>');
    });
});


Solution

  • you error is hidden here, in this piece of code, if you'll debug it line by line:

    var src = jQuery('.center123').find('img').attr('src');
    var res = src.split(" ");
    var src_first = res[0];
    

    in case there's no elements found, you'll get no src attributes found, which equals to undefined value stored in src_first variable.

    You need to introduce additional check of the result, which is stored within res[0]. split(" ") will work only on type {String}, it can't be applied to undefined.

    The simplest additional check may be coded like:

    // ...
    var src = jQuery('.center123').find('img').attr('src');
    if (! src) { // <== here's the additional check, the simplest case possible
        return;
    }
    var res = src.split(" ");
    var src_first = res[0];
    // ...