I've been looking for so long and found several answers that suggest using .on() as in $('.idOfMyElemenet').on() works even for elements that don't exist yet. But this doesn't seem to be finding the element. Am I doing something wrong?
The highest level <span> (in screenshot) does not exist until I click on a drop-down. Ultimately I'm trying to trigger an event when the user clicks on any of the <li> (aka selects an option from the drop-down).
$(document).ready(function () {
var test = "#select2-id_customer-results";
$(test).on("click", function() {
console.log('hello')
})
})
EDIT:
Thanks to Drew Baker - I think his second solution is the way to go. But not quite there yet...
From the select2 documentation
All public events are relayed using the jQuery event system, and they
are triggered on the <select> element that Select2 is attached to.
So I tried listening to it via the id (which doesn't seem to exist but would probably be id_customer) and the class. The class I added below did not work. Is there a way to listen to this using Jquery?
$(document).ready(function () {
// console.log($('#id_customer'));
$('.modelselect2 form-control select2-hidden-accessible').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
});
I'll answer your question, but then give you a better solution.
First, you need to make sure the thing you are attaching .on() to actually exists. I typically use a containing DIV or failing that body or html will work.
Secondly you are missing a parameter that tells jQuery the thing you are looking to watch to be clicked on. In this case, I'm assuming it is the UL tag with the ID you provided.
This should do what you want:
$(document).ready(function () {
$('body').on("click", "#select2-id_customer-results", function() {
console.log('hello')
})
})
But a better solution would be to use the Select2 API to have it tell you when something is selected. This will be way more reliable and should make your code work after upgrades to Select2.
Something like this:
$('select[name="customer"]').on('select2:select', function (e) {
var data = e.params.data;
console.log(data);
});
NOTE: #mySelect2 is probably not what you have. Use whatever ID you used to initialize Select2 in jQuery.
You can read more about that API here: https://select2.org/programmatic-control/events
if your element is dynamically generated and you want to target that specific element. You need to specify a static container/parent element to indicate where it belongs.
Try this:
$( '#dynamicallyAddedElement' ).on( 'click', '#wrapper', function () { ... });
//where #wrapper is a static parent element in which you add the dynamic links.
So, you have a wrapper which is hard-coded into the HTML source code:
PS. Hope I helped in some way.
If you need to trigger an event when click on <li> elements, you have to use that elements id or class as the selector. Check the below code:
$(document).ready(function () {
var test = ".select2-results__option";
$(test).on("click", function() {
console.log('hello')
})
})
It turns out this is an old bug in django-auto-complete.
The code below works. I have no idea why but now I can move on.
Note: the 'name' is the value of the select2 select element (see screenshot at bottom)
document.querySelector('select[name="customer"]').onchange=function() {
console.log("myselect2name changed");
};
Related
I am trying to target a class called 'horizontal-video' in a div within an AEM component and if the author has clicked a checkbox that has an ID of 'coral-id-540' I want to add a second class called 'flipped' to the div. Here is the code I wrote that isn't working. Could someone help me figure out why it's not working? The console does not show errors.
var x = document.getElementsByClassName("horizontal-video");
$('#coral-id-540').change(function(){
if($(this).is(":checked")) {
$(this).addClass("flipped");
} else {
$(this).removeClass("flipped");
}
});
It's quite possible you're not waiting for the DOM to completely load, (or at least have this bit of code below the element in question on the page during page load)
Is your code wrapped in $(document).ready(function(){ //your code });?
Also, be aware that any element that is dynamically added to the page by JavaScript/jQuery after page load will not have a listener attached using the method you're using.
To allow dynamically added elements to be included in your listener, you should target an ancestor node and add the listener to that node. In plain English: attach the listener to a "higher up" element. The safest (although slowest) node being document itself, but it's better to target something closer:
$(document).ready(function () {
var $horizontalVideo = $(".horizontal-video"); //You're using jQuery - why not use it here? Also, I always name jQuery objects with a `$` in front as a shorthand to know it's wrapped in a jQuery object. Plus, a more descriptive name will help you immensely.
//replace parent-of-coral with the ID of a parent element that you know exists on DOM ready:
$("#parent-of-coral").on("change", "#coral-id-540", function (e) { //get used to using "e" as the event variable for preventing default / stopping propagation / etc
$this = $(this); //cache $(this) reference rather than creating another jQuery object each time you use it
if ($this.is(":checked")) {
$this.addClass("flipped");
} else {
$this.removeClass("flipped");
}
});
});
You can do something like:
function myFunct(){/*.....*/}
$("body").on("click", "li.itemlist", function(){
alert("ping");
});
which would have all li.itemlist under body to have the click event.
Is there a way to convert:
var _OPTIONS_ = {
containment: "#stage",
start:function(){/*...*/},
drag:function(){/*...*/},
stop:function(){/*...*/}
};
$("li.itemlist").draggable(_OPTIONS_);
to:
$("body").on("draggable", "li.itemlist", _OPTIONS_);
EDIT: I have not tried the second one. I didnt think it would work because draggable is a JQuery function, not a standard js listener.
No, but there is another way to do it.
$("body").on("mouseenter","li.itemlist:not(.draginit)",function(){
$(this).draggable(_OPTIONS_).addClass("draginit");
})
The first time the element is moused over, the draggable widget will be applied to it.
I'd suggest using something better than body though, such as the ul.
Assuming I have a HTML link in my rows inside a datagrid or repeater as such
DoSomething
Now also assuming that I have handled the click event for all my DoSomethings in jQuery as such
$(".DoSomething").click(function (e) {
//Make my DoSomethings do something
});
What is the correct technique for passing data to the click event that is dependent on the link clicked?
Without jQuery you would typically do something like this.
DoSomething
but this technique obviously doesn't work in the jQuery case.
Basically my ideal solution would somehow add values for to the jQuery.Data property for the link clicked but doing so declaratively.
Use HTML5 data- attributes. jQuery support is built-in for 1.4.3+
http://api.jquery.com/data/#data2
click here
$('.product-link').click(function (e) {
alert($(this).data('productid'));
});
You could use the attr() function.
http://api.jquery.com/attr/
$("#Something").attr("your-value", "Hello World");
$("#Something").click(function (e) {
//Make my DoSomethings do something
var value = $(this).attr("your-value");
alert(value); // Alerts Hello World
});
your question was not clear to me but may be this will help
$(".DoSomething").click(function (e) {
//Make my DoSomethings do something
$(this).data("key","value");
//later the value can be retrieved like
var value=$(this).data("key");
console.log(value);// gives you "value"
});
I'm using jQuery to get a click on an 'a' element. I have a list of those links where each one has a class which by him I'm capturing the click.
I would like to know which of the links has been clicked (I have an attribute 'setid' for each link) and also get the point where the mouse has been clicked.
How could this be accomplished?
example of the code:
click me
$('.newItem').click(function (e) {
alert(e.attr('setid'));
});
EDIT:
OK, so to get the position I would use e.pageX
To use jQuery methods you have to wrap this with a call to jQuery.
$('.newItem').click(function () {
alert($(this).attr('setid'));
});
refer to the code given below:
document.getElementById("element_id").addEventListener("click",function(e)
{
console.log(e.srcElement.getAttribute("data-name"));
},false);
Like Skylar said in the comment to your question, you can use "data-" in front of your new attribute (which is HTML5 valid).
click me
Then in jQuery (v1.4.3+) you can get it like:
var setid = $(this).data("foo");
It's even a little nicer than attr() that other people have mentioned. See this for more examples - http://www.broken-links.com/2010/11/18/data-attributes-in-html-and-jquery/
You're on the correct path.
$(function(){
$('.newItem').click(function () {
alert( $(this).attr('setid') );
})
});
Your code is almost right to get the attribute. The only thing missing is wrapping this (a DOM element) in the jQuery wrapper so you can use jQuery functions. $(this).attr('setid') should work.
To get the page coordinates, use the pageX and pageY properties of the event object. So:
$('.newItem').click(function (e) { // e is the event object
alert($(this).attr('setid'));
alert(e.pageX);
alert(e.pageY);
});
See the documentation on the Event object.
I think I've been too much time looking at this function and just got stuck trying to figure out the nice clean way to do it.
It's a jQuery function that adds a click event to any div that has a click CSS class. When that div.click is clicked it redirects the user to the first link found in it.
function clickabledivs() {
$('.click').each(
function (intIndex) {
$(this).bind("click", function(){
window.location = $( "#"+$(this).attr('id')+" a:first-child" ).attr('href');
});
}
);
}
The code simply works although I'm pretty sure there is a fairly better way to accomplish it, specially the selector I am using: $( "#"+$(this).attr('id')+" a:first-child" ). Everything looks long and slow. Any ideas?
Please let me know if you need more details.
PS: I've found some really nice jQuery benchmarking reference from Project2k.de here:
http://blog.projekt2k.de/2010/01/benchmarking-jquery-1-4/
Depending on how many of these div.click elements you have, you may want to use event delegation to handle these clicks. This means using a single event handler for all divs that have the click class. Then, inside that event handler, your callback acts based on which div.click the event originated from. Like this:
$('#div-click-parent').click(function (event)
{
var $target = $(event.target); // the element that fired the original click event
if ($target.is('div.click'))
{
window.location.href = $target.find('a').attr('href');
}
});
Fewer event handlers means better scaling - more div.click elements won't slow down your event handling.
optimized delegation with jQuery 1.7+
$('#div-click-parent').on('click', 'div.click', function () {
window.location.href = $(this).find('a').attr('href');
});
Instead of binding all the clicks on load, why not bind them on click? Should be much more optimal.
$(document).ready(function() {
$('.click').click(function() {
window.location = $(this).children('a:first').attr('href');
return false;
});
});
I would probably do something like;
$('.click').click(function(e){
window.location.href = $(this).find('a').attr('href');
});