Friday 15 June 2018

Pure JavaScript instead of jQuery - ready, on, click and end selector




I have in jQuery:



$(document).ready(function() {
$(document).on('click', "[id$='someId']", function () {

console.log($(this).val());
})
})


How can I write it in pure JavaScript?




$(document).ready(function()





Should I use "ready" in pure JavaScript?




$(document).on




How can I use "on"? I have to add dynamic elements, so in jQuery I must use "on".



I would like write this in accordance with ES6.



Answer



Use addEventListener instead of on:



document.addEventListener('DOMContentLoaded', function () {
document.body.addEventListener('click', function (e) {
if (e.target.matches("[id$='someId']")) {
console.log(e.target.value);
}
});
});



The event delegation makes it a bit more complex, but it should do the trick.


No comments:

Post a Comment

php - file_get_contents shows unexpected output while reading a file

I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print &q...