I converted a jQuery plugin to Vanilla JS. It works pretty well but at least I have two quick questions.
1- Is it safe to use?
2- Why does it run slowly than jQuery?
I tried to clear my doubts regarding but not able to clarify it well. That is why I asked.
Here’s the code (Pure JS) I’m using:
document.addEventListener('DOMContentLoaded', function()
{
var elements = document.querySelectorAll('.reactions-icon');
elements.forEach(function(element)
{
element.addEventListener('click', function(event)
{
event.preventDefault();
var main = this.parentElement.parentElement;
var vote_type = main.dataset.type;
var voted = main.dataset.vote;
var type = this.dataset.action;
var style = main.dataset.style;
var data = new FormData();
data.append('action', 'reaction_save_action');
data.append('nonce', main.dataset.nonce);
data.append('type', type);
data.append('post', main.dataset.post);
data.append('voted', voted);
data.append('style', style);
data.append('vote_type', type);
var xhr = new XMLHttpRequest();
xhr.open('POST', '/ajax.php');
xhr.onload = function()
{
if (xhr.status === 200) {
var responseData = JSON.parse(xhr.responseText);
if (responseData.success) {
var postElement = document.querySelector('.reactions-post-' + main.dataset.post);
postElement.innerHTML = responseData.data.html;
main.setAttribute('data-vote', 'yes');
main.setAttribute('data-type', 'unvote');
document.querySelectorAll('.reactions-box-2').forEach(function(box) {
box.classList.add('unvote');
box.removeEventListener('click', boxClickHandler);
});
}
}
};
xhr.send(data);
function boxClickHandler() {
main.setAttribute('data-vote', 'no');
main.setAttribute('data-type', vote_type);
document.querySelectorAll('.reactions-box-2').forEach(function(box) {
box.classList.remove('unvote');
box.addEventListener('click', boxClickHandler);
});
}
document.querySelectorAll('.reactions-box-2').forEach(function(box) {
box.addEventListener('click', boxClickHandler);
});
});
});
});
It works pretty well as I said, and here’s the jQuery code:
jQuery(document).ready(function($)
{
$(document).on("click", ".reactions-icon", function (event)
{
event.preventDefault();
var t = $(this),
main = t.parent().parent(),
vote_type = main.data("type"),
voted = main.data("vote"),
type = $(this).data("action"),
style = main.data("style");
$.ajax({
url: "/ajax.php",
dataType: "json",
type: "POST",
data: { action: "reaction_save_action", nonce: main.data("nonce"), type: type, post: main.data("post"), voted: voted, style: style, vote_type: type },
success: function (data) {
if (data.success) {
$(".reactions-post-" + main.data("post")).html(data.data.html);
main.attr("data-vote", "yes").attr("data-type", "unvote");
$(".reactions-box-2").addClass("unvote").off("click");
}
},
});
});
});
I think a little help would be nice…