I have the following v-for and when i add a new comment I want to scroll to that comment but I'm getting the following error in console:
Cannot read property 'top' of undefined
This is the line causing the error in my add method:
$('html, body').animate({scrollTop: $("#comment-" + response.data.id).offset().top}, 2000);
I've checked console and response.data.id is not empty so it must be to do with jquery not recognising the added element. any ideas?
<ul class="list-inline">
<li v-for="(comment, index) in comments"
:key="comment.id"
:id="'comment-' + comment.id">
<span v-html="comment.comment"></span>
</li>
</ul>
var vm = new Vue({
el: '#root',
data: {
comments: [
{
"id": 2,
"comment": "blah...",
},
{
"id": 4,
"comment": "blah...",
}
{
"id": 6,
"comment": "blah...",
}
]
},
methods: {
add: function (comment) {
axios.post("api/comments/add, { comment: comment })
.then((response) => {
this.comments.push(response.data);
$('html, body').animate({scrollTop: $("#comment-" + response.data.id).offset().top}, 2000);
})
.catch((error) => {});
}
}
});
response.data.id? My guess is that#comment-Xdoesn't exist and therefore.offset()returnsundefined.this.comments.push(response.data);before i call the scroll function.response.data.idhas the id value of the newly created comment e.g.8#comment-Xdoesn't exist yet when you try to scroll to it.