I am having trouble targeting elements within jQuery ui-datepicker with the plugin WooCommerce Bookings.
Every time I target it using JavaScript it returns null, so the EventListener can't be executed.
However, if I target anything outside the jQuery ui-datepicker I can actually execute the events created with the JS and jQuery.
This is the first time I have encountered something like this and I'm finding it very unusual.
There are the two snippets I have used to test whether or not it can identify the element:
jQuery('.hasDatepicker').on('click', function() {
alert('hi');
});
function showVolunteers() {
alert("hi");
}
document.querySelector(".hasDatepicker").addEventListener('click', showVolunteers);
Here is a JS fiddle with the HTML for the datepicker: https://jsfiddle.net/e5dnru0e/3/
The datepicker is nested within a fieldset, which I can target so I thought maybe I could try use jQuery('fieldset div.ui-datepicker') but that did not work either.
To triple check I was using the correct selector I tried using some CSS and the CSS works perfectly, so there isn't something wrong with my selector.
Is it possible that it has somehow restricted jQuery to be used within this datepicker.
Any help or suggestions will be greatly appreciated.
When your are registering an event for any DOM element then it should be present in DOM at the time of registering.
In case of dynamic controls (which are injected to DOM after DOM ready event) you can use following syntax of jquery for registering an event.
$(document).on('click','.ui-datepicker', function() {
alert('hi');
});
Above code attaching click event on document (which is always present on Document ready). Second parameter of on function is [selector] ie. .ui-datepicker
Instead of document, you can attach click event on any other DOM element which is going to
present while registering an event.
i.e
$('.datepicker-container').on('click','.ui-datepicker', function() {
alert('hi');
});
Related
I am using jQuery 2.2.4. I have three .note_edit elements in my page, added dynamically after page load (they are part of CartoDB infowindows).
I am using the following code in the console to check that the elements exist, which they do:
$("body .note_edit");
Then I am trying to add a dynamic event in the console as follows:
$('body').on('click', '.note_edit', function(e) { e.preventDefault(); console.log('whatever'); });
But when I click on the elements, nothing happens - no console output.
What might be going wrong here? There aren't any other JS errors in the console, the elements definitely exist... what could it be?
Check for other events bound to the elements. Can I find events bound on an element with jQuery?
I suspect there is a e.stopPropagation() preventing body from being reached.
EDIT: The Issue has been solved, as it turns out, the Select2 library had a custom command for this typa thing:
$("#element").on("change", function (e) { ... }
// Defined as "change"
I'm using a dropdown menu library called Select2 3.2. In short, the code takes a bunch of select and option tags, and generates a cool drop down search list.
However, after the site is rendered; when I click 'view source', all my select and option tags are still there, but when I right click the fancy new generated menus themselves and select "inspect element" (using google chrome), the html is TOTALLY different.
I think that this is causing the problem, all this new code is rendered from the custom library's JS, and after my jQuery event commands.
Specifically, here is my command:
$(document.body).on('click', '.select2-result-label', function() {
var name = $(this).text();
var post_to = '/myurl/';
$.post(post_to, { dat: dat},
function(response) {
...
}, 'json'
)
I believe the on() method takes care of this kinda stuff but apparently not, any help would be appreciated!
RELEVANT EDIT:
Here is a blurb from another Stack Overflow post:
The view page source page shows you the exact text that
was returned by the server.
Inspect element actually shows you the fully rendered DOM tree.
Knowing that, maybe solving this will be easier.
Here is a JS Fiddle related:
http://jsfiddle.net/JpvDt/47/
Try to make the alert "worked" appear when you click on an "x" in the multi bar.
Right now my code has it to register the class which contains the x's.
$(document.body).on("click", ".select2-search-choice-close", alert("worked"));
Scenario 1:
Your problem is may be you bind on method for whole DOM which is really BAD. So always try to bind that to the closest div (closest parent element) which your controls are exist.
About Event performance from Jquery API says like below.
Attaching many delegated event handlers near the top of the document
tree can degrade performance. Each time the event occurs, jQuery must
compare all selectors of all attached events of that type to every
element in the path from the event target up to the top of the
document. For best performance, attach delegated events at a document
location as close as possible to the target elements. Avoid excessive
use of document or document.body for delegated events on large
documents.
Scenario 2:
Call your on event like below (with off event).
$(#yourElement).off('click').on('click', '.select2-result-label', function() {
var name = $(this).text();
var post_to = '/myurl/';
$.post(post_to, { dat: dat},
function(response) {
...
}, 'json'
)
I hope this will help to you.
As it turns out, the Select2 library had a custom command for future changes to the toolbar.
Read more here: http://ivaynberg.github.com/select2/#programmatic
It's vital to note that many standardized jQuery calls won't work with Select2, you must use their custom set-up.
$("#element").on("change", function (e) { ... }
// Defined as "change"
Just replace $(document.body) by $(document)
I have the following code:
var $reviewButton = $('span.review_button');
$reviewButton
.live('click',
function(){
$('#add_reviews').show();
}
)
Later in the script, I use an AJAX call to load some content and another instance of $('span.review_button') enters the picture. I updated my code above to use '.live' because the click event was not working with the AJAX generated review button.
This code works, as the .live(click //) event works on both the static 'span.review_button' and the AJAX generated 'span.review_button'
I see however that .live is depracated so I have tried to follow the jquery documentations instructions by switching to '.on' but when I switch to the code below, I have the same problem I had before switching to '.live' in which the click function works with the original instance of 'span.review_button' but not on the AJAX generated instance:
var $reviewButton = $('span.review_button');
$reviewButton
.on('click',
function(){
$('#add_reviews').show();
}
)
Suggestions?
The correct syntax for event delegation is:
$("body").on("click", "span.review_button", function() {
$("#add_reviews").show();
});
Here instead of body you may use any static parent element of "span.review_button".
Attention! As discussed in the comments, you should use string value as a second argument of on() method in delegated events approach, but not a jQuery object.
This is because you need to use the delegation version of on().
$("#parentElement").on('click', '.child', function(){});
#parentElement must exist in the DOM at the time you bind the event.
The event will bubble up the DOM tree, and once it reaches #parentElement, it is checked for it's origin, and if it matches .child, executes the function.
So, with this in mind, it's best to bind the event to the closest parent element existing in the DOM at time of binding - for best performance.
Set your first selector (in this case, div.content) as the parent container that contains the clicked buttons as well as any DOM that will come in using AJAX. If you have to change the entire page for some reason, it can even be change to "body", but you want to try and make the selector as efficient as possible, so narrow it down to the closest parent DOM element that won't change.
Secondly, you want to apply the click action to span.review_button, so that is reflected in the code below.
// $('div.content') is the content area to watch for changes
// 'click' is the action applied to any found elements
// 'span.review_button' the element to apply the selected action 'click' to. jQuery is expecting this to be a string.
$('div.content').on('click', 'span.review_button', function(){
$('#add_reviews').show();
});
this pattern href="javascript:stop(this); pass the hyperlink object to stop function, but i also want to pass invoked event to that function. how can i do that? my records are getting load through ajax so cant attach .click(function(event){}) with it. and if i attach click on each AJAX call then web slows down on IE6.
please guide me
Thanks
You have jQuery so you can use delegates/live events instead of inline events or those nasty javascript: hrefs:
$('#parent').on('click', 'a', function(e) {
// you can use this and e (the event) here
});
#parent needs to be an element that already exists and will contain the newly added elements. a is the selector to match the elements inside #parent on which you want the click events to trigger. You may use $(document) instead of $('#parent') to resemble .live() from older jQuery versions, but using a parent element that is closer to the inner elements is better for performance reasons.
I'm still new to jQuery and I'm wondering how come the jQuery functions called inside .ready() work just fine but not outside?
For example, this would work:
$(document).ready(function() {
$('#field1').click(function() {
$('#result').load('/random_post #post');
});
});
But this won't:
$('#field1').click(function() {
$('#result').load('/random_post #post');
});
You cannot access the DOM until the document is fully parsed and the DOM constructed. That includes modifying any elements – such as #field1 and #result.
Since $(document).ready(..) is long and may be hard to remember, you can also use the short form $(onReadyFunction), i.e.
$(function() {
$('#field1').click(function() {
$('#result').load('/random_post #post');
});
});
By the way, jQuery does no magic here: It just registers your function to be called when DOMContentLoaded (or equivalent) event is triggered by the parsing and construction of the DOM tree.
How and if it works will depend on the order of which scripts and elements are laid out in your HTML, and it might also be affected by parameters outside your control (e.g. how the browser is programmed to behave).
I 'd hazard a guess that this script appears in your page before the element with id="field1" that gets a click handler added; this causes the script to run and find no such element in the document tree (yet). The element gets added after the script runs, which is why jQuery finds it just fine after the whole document has loaded.
If you move this script at the very end of your page it should work (although of course the correct solution is to use the document ready event, as in your first snippet).
The ready function is executed when the dom tree has been created. You get an error in your second piece of code because the dom tree element with id filed1 has not been created yet, i.e. the page hasn't loaded yet.