How does the click event work in JQuery?
I mean, I learned how to make chaining method but I have no idea of how make the click event like this:
MyLibrary("selector").click(function(){
console.log("hello");
});
I guest that if I learned this, i'll know how does blur, mouseover, etc etc, works as well.
Please I hope you help me learn, I searched for answer but i could not find any or maybe I was asking in the wrong way.
UPDATE
I know how to use jQuery, BUT WHAT I ASKED WAS how can I make it? I mean, I want to create a library and I want to add a click event like jQuery does.
I did chaining method like this:
Find().UserByName("Bob").Write("DivOrInputObject's ID").UserByPass("pass").Write("DivOrInputObject's ID");
But while writing the code, It came to my mind how can I make a click event? In simple words, I want to imitate click() event like jQuery does and add it to my library.
I am assuming that you are writing your own jQuery. So if your MyLibrary object have selected element under MyLibrary.el then you can have chainable click handler like this:
click: function(handler){
this.el.addEventListener('click', handler.bind(this.el));
return this;
},
This will bind this inside the handler to the element itself. Just like jQuery
Here is this code in action: http://jsbin.com/ahinow/1/
Related
I need to change behavior of jQuery library (date range picker), it have code like this:
box.find('.month').off("change").change(function(evt) {
dateChanged($(this));
});
box.find('.year').off("change").change(function(evt) {
dateChanged($(this));
});
Those are two select elements. It don't return false and functions inside handler don't access the event. But for some reason my events that use delegation doesn't work. They are ignored.
$picker.on('change', 'select', function() {
console.log('CHANGE');
});
The console log is not executing, but if I remove previous lines from the library, my event delegation code works fine.
NOTE: $picker is object in my code that is parent of box element. But I also have event added on $(document) that is also not working.
First time I see something like this. Adding event directly to element, prevents event propagation. Can someone explain what is happening here? Is this documented anywhere?
This happens in Firefox and Chrome.
If someone need simple example, I can create one. But thought that this is self explanatory.
EDIT: I've created a simple reproduction and it works fine. I have complex application with a lot of files (R Shiny Application), but I don't see any change events in dev tools. Are there any way of making the event not propagate? Maybe using event capturing. What should I search for in order to find the code that is preventing the events from propagating?
I am not great at javascript/jquery for the most part but I know how to get some software to work. But my issue is that I have a whole bunch of
$("body").on("click", "button#thisid", function(event) {
//do stuff here
});
There are alot of the on clicks that use jquery post and get functions but they all have tiny and simple differences that i need to have get sent through. I dont want every single button to have an onclick event but I am not sure how to bind the event to a large list of items that need to have it attached to.
I have been trying to come up with some way to slim all these down but I want to have the best approach instead a whole bunch of crash and fails. So I am reaching out to people who know more than me in order to lead me in the correct path.
Please help
Considering your elements are dynamically injected, you will need to apply the click handler to an element that always exist on page load:
$(document).ready(function() {
$(document).on("click", "button.target", function() {
console.log($(this)[0].id);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="1" class="target">One</button>
<button id="2" class="target">Two</button>
In the above example, the click handler is applied to document, and triggers whenever a button element with the class of target is clicked, running the code inside the function.
To combine the .get() and .post() functions, you'll have to find synonymous data. Keep in mind that you have access to $(this), so you can extract the relevant ID if need be :)
Hope this helps!
I dont exactly get what you want to do...
But the $("body") is the jquery selector which defines on which elements your listener will be bound to.
So if you want to create a listener for more different elements the probably easiest solution is creating a class like "listenedElement" which you give to every element you want the listener to react to and write write the selector like this
$('.listenedElement').on( "click", function() {});
If you just look for click listeners this one looks pretty nice as well:
https://api.jquery.com/click/
A nice way I find is having a one line for each button like so:
$('#model').on('click', openModel());
$('#openDropdown').on('click', openDropdown());
$('#shoppingCart').on('click', shoppingCart());
And then defining each of these functions:
function openModel() {
// Stuff here
}
function openDropdown() {
// Stuff here
}
function shoppingCart() {
// Stuff here
}
So instead of writing the function as a parameter, I find it neater to just do it separately and call it like above.
I was messing around with jQuery and event handlers, when I noticed this:
That uses jQuery, and without it:
How does the popup get a bar saying jQuery? Do browsers have integrated jQuery support to detect that? Or is there some way to name event handlers? I want to have my event display some other text, like how jQuery does.
NOTE: I don't want to use jQuery, as I want to know how jQuery does it.
I am not sure about what you are trying to do, but in Javascript you can always name functions
Example:
function myEventHandler(event) {
alert('event handler');
}
myEventHandler is the name of the function.
Hope this helps a little,
best,
Carsten
You can have custom names for your events if you want. We can use the trigger function for the same purpose.
Suppose you want to raise myEvent on <div id="my_div">.
We can simply
$("#my_div").trigger('myEvent');
and have a listener for the event:
$("#my_div").on('myEvent', function(event){
//Event handler
});
You can find some good documentation here -
https://learn.jquery.com/events/introduction-to-custom-events/
And this SO answer covers it thoroughly -
Custom events in jQuery?
I'm talking about the following:
.unbind().click(function () {
// Do something
}
It looks a bit dodgy to me, however it makes sense: the developer wants to first remove any events bound to the element and then bind a click event.
Is there a better solution for this issue? Or correct my way of thinking.
It's not really good practice, because you do not control which click events get unbound. There are two different approaches to improve this:
Use event namespaces (faster)
You can use a namespace to control you unbind just the click event you're going to bind again:
$(selector).off('click.namespace').on('click.namespace', function(e) { //...
Use classes (fastest)
Use classes added to the link to mark it as registered (this does not unbind previously bound events, but it helps preventing multiple event bindings, which is the issue in most cases you would use off (unbind) before on (bind):
$(selector).not('.registered').addClass('registered').on('click', function(e) { //...
You can even turn this into a little sexy plugin, writing:
$.fn.register = function(register_class) {
register_class || (register_class = 'registered'); // lets you control the class
return this.not('.' + register_class).addClass(register_class);
};
Like this, you can just call register on every selector:
$(selector).register().on('click', function(e) { //...
Or with a specific class, if «registered» is taken:
$(selector).register('special_handler_registered').on('click', function(e) { //...
Performance?
If you wonder about the performance of the different handlers:
Check out this performance test here
I followed this approach whenever I had to "renew" some button, link, ect., behavior, and I think there's nothing wrong with it.
But be aware that with your code you'd be removing every handler attached to the element(s). So, instead:
$(selector).unbind('click').click(function(){
// do something
})
Well, at least it is good practice to specify which event handlers should be unbinded. So if there was some click event hendler and we want to unbind only it, then we can use unbind('click').
As there can be some other handlers in addition to yours, it make sense to use namespaces.
$(selector).off('click.myns').on('click.myns', function() {....})
or
$(selector).unbind('click.myns').bind('click.myns',function() {...})
This way you will only touch your own handler and not some others, for instance added by jquery plugins
I usually try to used named event functions where ever possible in order to be able to unbind them explicitly:
$('a').unbind('click.myfunc').bind('click.myfunc', function(evt) { ... });
This way you could add this binding to an init-function that could be executed multiple times (handy for situations where you can't use delegate for whatever reason).
In general I would't try to unbind every event or even every handler of a certain event if I don't need to.
I'm also trying to stay current and replace all the bind/unbind calls with on/off ;-)
I want to make 'select' element to behave as if it was clicked while i click on a completely different divider. Is it possible to make it act as if it was clicked on when its not??
here is my code
http://jsfiddle.net/fiddlerOnDaRoof/B4JUK/
$(document).ready(function () {
$("#arrow").click(function () {
$("#selectCar").click() // I also tried trigger("click");
});
});
So far it didnt work with either .click();
nor with the .trigger("click");
Update:
From what i currently understand the answer is no, you cannot. Although click duplicates the functionality it will not work for certain examples like this one. If anybody knows why this is please post the answer below and i will accept it as best answer. Preferably please include examples for which it will not work correctly.
You can use the trigger(event) function like ("selector").trigger("click")
You can call the click function without arguments, which triggers an artificial click. E.g.:
$("selector for the element").click();
That will fire jQuery handlers and (I believe) DOM0 handlers as well. I don't think it fires It doesn't fire handlers added via DOM2-style addEventListener/attachEvent calls, as you can see here: Live example | source
jQuery(function($) {
$("#target").click(function() {
display("<code>click</code> received by jQuery handler");
});
document.getElementById("target").onclick = function() {
display("<code>click</code> received by DOM0 handler");
};
document.getElementById("target").addEventListener(
'click',
function() {
display("<code>click</code> received by DOM2 handler");
},
false
);
display("Triggering click");
$("#target").click();
function display(msg) {
$("<p>").html(msg).appendTo(document.body);
}
});
And here's a version (source) using the onclick="..." attribute mechanism for the DOM0 handler; it gets triggered that way too.
Also note that it probably won't perform the default action; for instance this example (source) using a link, the link doesn't get followed.
If you're in control of the handlers attached to the element, this is usually not a great design choice; instead, you'd ideally make the action you want to take a function, and then call that function both when the element is clicked and at any other time you want to take that action. But if you're trying to trigger handlers attached by other code, you can try the simulated click.
Yes.
$('#yourElementID').click();
If you added the event listener with jquery you can use .trigger();
$('#my_element').trigger('click');
Sure, you can trigger a click on something using:
$('#elementID').trigger('click');
Have a look at the documentation here: http://api.jquery.com/trigger/
Seeing you jsfiddle, first learn to use this tool.
You selected MooTools and not jQuery. (updated here)
Now, triggering a "click" event on a select won't do much.
I guess you want the 2nd select to unroll at the same time as the 1st one.
As far as I know, it's not possible.
If not, try the "change" event on select.