I have two javascript file one with the functions and another with the eventlistener. This is how I declare them
<body>
<script src="../script/Main%20Functions.js"></script>
<script src="../script/Main-events.js"></script>
</body>
Main Functions.js
checklike(userId,postId);
function checkLike(userId, postId) {
$.ajax({
type: "POST",
url: "../Main.asmx/get_liked",
data: "{'userID':'" + userId + "', 'postID':'" + postId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var result = response.d;
console.log('ok');
$.each(result, function (index, data) {
var liked = data.liked;
if (liked == true) {
$("#" + postId).prev().parent("button").css("background", "#ccc");
}
else {
$("#" + postId).prev().parent("button").css("background", "white");
}
});
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Function Error "checkLike"');
}
});
}
Main-events.js
const d = document.querySelector.bind(document);
const D = document.querySelectorAll.bind(document);
const logOut = d('.lOut h3');
const iFrame = d('#if1');
const alias = d('.codename-label h2');
const monito = d('.monito-label');
const monitoChecklists = D('.monito-checklist');
const displayPicture = d('#displayPic');
const btnReveal = d('.btn-reveal');
const btnSubmit = d('.btn-submit');
const btnLike = D('.buttonLike');
console.log('ok2');
btnLike.forEach(function (like) {
like.addEventListener('click', function (e) {
console.log(this);
})
});
but when I open the html the console.log('ok2');
executes first not the console.log('ok')
. Is there a way on telling the javascript to load specific file first before executing the file for eventlistener
?
EDIT 1: The adding of eventlistener
for the btnLike
loads first before the javascript added the elemet on the page.
EDIT 2: Okay upon investigation
Before trying eventlistener I use this jquery code
$(document).on('click', '.buttonLike', function () {
var color = $(this).css("background-color");
var id = $(this).find(".postID").attr("id");
if (color == "rgb(204, 204, 204)") {
$(this).css("background-color", "white");
var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) - 1;
if (number > 1) {
number = number + " Likes";
}
else {
number = number + " Like";
}
$("#" + id).html(number);
Remove_Like(id);
}
else {
$(this).css("background-color", "#ccc");
var number = parseInt($("#" + id).html().substring(0, $("#" + id).html().indexOf(" "))) + 1;
if (number > 1) {
number = number + " Likes";
}
else {
number = number + " Like";
}
$("#" + id).html(number);
Add_Like(id);
}
});
it works fine and I found out that it uses the document
and check if the target
has class name .buttonLike
am i right?