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' );
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With