I am trying to use Coffeescript, but I am having a problem on my web application. Its methods are not called until I reload the page.
I think that what is missing is the $(document).ready(function () {
part, but I couldn't find how to do it in the web.
file_name.js (works great)
$(document).ready(function () {
$(document).on('click', '.add_fields', function(event) {
event.preventDefault();
/* Act on the event */
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
});
});
file_name.coffee (doesn't work)
jQuery ->
$('form').on 'click', '.add_fields', (event) ->
time = new Date().getTime()
regexp = new RegExp($(this).data('id'), 'g')
$(this).before($(this).data('fields').replace(regexp, time))
event.preventDefault()
How can I fix this?
Answer: Use the DOMContentLoaded Event You can utilize the JavaScript Window's DOMContentLoaded event to construct $(document). ready() equivalent without jQuery.
Why document ready is deprecated? As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated. This is because the selection has no bearing on the behavior of the . ready() method, which is inefficient and can lead to incorrect assumptions about the method's behavior.
The key difference between $(document). ready() and $(window). load() event is that the code included inside onload function will run once the entire page(images, iframes, stylesheets,etc) are loaded whereas the $(document). ready() event fires before all images,iframes etc.
$(document).ready ->
See example at https://github.com/jashkenas/coffeescript/blob/master/documentation/site/docs.coffee#L16
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With