Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: Cannot read property 'scrollHeight' of undefined

Why am I getting this error:

Uncaught TypeError: Cannot read property 'scrollHeight' of undefined.

The "Read more" button returns me to the top of the page instead of changing the height of my <div> element. How do I fix this?

This is my code:

function piki( $atts, $content = null ) {
{ ?>
<script type="text/javascript">
var h = jQuery('#piki')[0].scrollHeight;


jQuery('#more').click(function(e) {
    e.stopPropagation();
    jQuery('#piki').animate({
        'height': h
    })
});

jQuery(document).click(function() {
    jQuery('#piki').animate({
        'height': '50px'
    })
})
</script>
<?php }
    $url = '/?s=';
    $str = '';

    $output = array();
    $count = 0;

    foreach (explode(", ",$content) as $content) {
        $count++;
        $output[] = "<a href='" . $url . $content . "'>" . $content . "</a>";
        if ($count == 50) {
            break;
        }
    }

    return '<div id="piki" class="piki">'.implode(", ", $output).'</div><a id="more" style="float: left;" href="#">Read more</a>';
}
add_shortcode( 'piki', 'piki' );
like image 669
user3476062 Avatar asked Mar 29 '14 15:03

user3476062


1 Answers

The problem is that jQuery('#piki')[0] is not selecting any elements. So when you try to get scrollHeight, you are trying to get a field from an undefined value. This is because the code in <script> executes before the browser has processed the <div id="piki"... element. If you moved <script> to that it appears and executes after the div, then the JavaScript should execute without error.

like image 134
Louis Avatar answered Sep 28 '22 19:09

Louis