I'm new to jQuery and JavaScript in general. I noticed that if you insert an element via jQuery into the DOM and try to perform an action on that element later, it fails. For example:
I am adding a class of "listenToField" to all the input elements on the page:
$(function() {
$('input').addClass('listenToField');
});
Then when I add the second function:
$(function() {
$('input').addClass('listenToField');
// second function
$('.listenToField').keydown(function() {
alert('Hi There')
});
});
It does not alert 'Hi There'.
However if I hardcode the class "listenToField" into the HTML inputs, the alert works. How can I still have it work when jQuery inserts the class dynamically without resorting to hard coding?
jQuery's syntax is designed to make it easier to navigate a document, select DOM elements, create animations, handle events, and develop Ajax applications. jQuery also provides capabilities for developers to create plug-ins on top of the JavaScript library.
$() = window. jQuery() $()/jQuery() is a selector function that selects DOM elements. Most of the time you will need to start with $() function. It is advisable to use jQuery after DOM is loaded fully.
jQuery is a JavaScript library designed to simplify HTML DOM tree traversal and manipulation, as well as event handling, CSS animation, and Ajax. It is free, open-source software using the permissive MIT License. As of Aug 2022, jQuery is used by 77% of the 10 million most popular websites.
Try jQuery's live
method.
The live()
method assigns events to elements that exist, and ones that will be created.
http://api.jquery.com/live/
$('.listenToField').live('keydown', function() {
alert('Hi there!');
})
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