I currently have user articles that I load in from my mySQL database, which includes the title of the article and the cover image the user submitted for the article. When the user hovers over the article for one second, I want a "preview" of the article to show, which includes some of the text of the article, the topic of the article, the word count, and the number of likes on the article. I'm having trouble coming up with a function that executes this ajax request only if the user has their mouse over the article for one second (shortened for simplicity):
$(".articles").on("mouseenter", ".article-container-divs", function() {
setTimeout(function() {
$.ajax({
url: 'includes/articles/getArticlePreview.php',
type: 'POST',
data: {articleId: articleId, idUsers: idUsers},
dataType: 'json',
success: function(data) {
data.forEach(function(item) {
var wordCount = item.article.split(' ').length;
var topic = item.topic.slice(0,1).toUpperCase() + item.topic.slice(1).toLowerCase();
thisElement.find(".previewTopic").html("<span class='previewStyle'>Topic:</span> " + topic);
thisElement.find(".previewWordCount").html("<span class='previewStyle'>Word Count:</span> " + wordCount);
thisElement.find(".previewLikes").html("<span class='previewStyle'>Likes:</span> " + item.voteCount);
thisElement.find(".previewArticle p").html(item.article);
});
}
});
}, 1000);
});
I tried including a setTimeout()
function, which executes the AJAX call after one second. The only problem is it executes it regardless of whether the user takes their mouse off the article or not. When the user takes their mouse off the article, I want it to cancel if the user hasn't hovered for at least one second. Any suggestions?