I've used el.one('click', fn) in my codes. Now I need to refresh .one() event. I mean I want to call fn several times per clicking on el in the same loaded page.
I know, there is .on() event which sounds good in my case. But not really, I need .one() in general. Just few times I need to force .one() to acts like .on().
Ok well, is there any solution?
You could turn on .on() for as long as you need it to perform that way, and then do .off() to turn it back off.
Example:
var aFunc = function() { console.log('click!'); };
$("#foo").one("click", aFunc);
// some other stuff happens and when you need it...
$("#foo").on("click", aFunc);
// now you don't want it anymore
$("#foo").off("click", aFunc);
This is completely untested, but I think it might work.
It's important to note that to turn a handler .off(), you can't supply an anonymous function to .on(), that's why the function variable.
Related
I call an external js file. This js file already has a (document).click function. I want to have an (document).click within the main js.
external js:
$(document).click(function() {
//do stuff
});
I do not use global variables. What's the best way to have $(document).click function in the external file and also to add an $(document).click function within the main js?
You can have both. As long as nobody stops propagation, both event handlers will run.
Do post the code if you still have any trouble.
Expanding the answer a bit:
There is in fact a way (the wrong way) to do click event handlers that supports only one at a time. If you do:
element.onclick = function () {alert('a')};
And then
element.onclick = function () {alert('b')};
You will get only one alert (saying 'b'). Which is why you should never use that. This is a remnant of a time when nobody knew what they were doing. It's 2015, the less we talk about it the better.
Now, when you use the proper way of registering event handlers:
element.addEventListener('click', function () {alert('a')});
element.addEventListener('click', function () {alert('b')});
You'll get both alerts.
To clear up any confusion, it's worth mentioning that jQuery uses the same old addEventListener internally when you do $(element).click(f) or $(element).on('click', f) or however it works today.
You can add 'click' event on both the file,but the problem is, when
you click on that particular element both the handlers will fire on
the same time If i am not wrong, both handler will work differently
and should not fire at same time.
Best way use Event trigger with different name spaces of events.
$(document).on('click.func1',function(){
func1();
});
$(document).bind('click.func2',function(){
doStuff2();
});
Then when you need to trigger you can choose order.
$(document).trigger('click.func1').trigger('click.func2');
Or you can trigger both event on same time:
$(document).trigger('click');
If you want to click a link with jQuery, you can use one of the following methods:
$('a').click();
$('a').trigger('click');
Which is better? (performance, browser support, i.e.)
There seems to be none, performance wise.
See: http://forum.jquery.com/topic/a-trigger-click-vs-a-click
This method is a shortcut for .bind('click', handler) in the first
variation, and.trigger('click') in the second.
Except you can extend the trigger command.
Seems like i was mistaking.
Since click is actually calling trigger, if no function is called.
See: jQuery advantages/differences in .trigger() vs .click()
And for performace results, #VisioN linked to this: http://jsperf.com/click-vs-trigger-click
So, basicly using trigger is the fastest way, also i think it actually tells what you are doing, instead of just doing it.
http://forum.jquery.com/topic/a-trigger-click-vs-a-click
In this form they are the same. As the api reference states:
This method is a shortcut for .bind('click', handler) in the first variation, and .trigger('click') in the second.
The second can also be used to attach a function to the event.
Exactly the same. But I prefer $('a').bind('click', function(){});
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.
So, you have a page:
<html><head>
<script type="text/javascript" src="jquery.1.3.2.js"></script>
<script type="text/javascript">
$(function() {
var onajax = function(e) { alert($(e.target).text()); };
var onclick = function(e) { $(e.target).load('foobar'); };
$('#a,#b').ajaxStart(onajax).click(onclick);
});
</script></head><body>
<div id="a">foo</div>
<div id="b">bar</div>
</body></html>
Would you expect one alert or two when you clicked on 'foo'? I would expect just one, but i get two. Why does one event have multiple targets? This sure seems to violate the principle of least surprise. Am i missing something? Is there a way to distinguish, via the event object which div the load() call was made upon? That would sure be helpful...
EDIT: to clarify, the click stuff is just for the demo. having a non-generic ajaxStart handler is my goal. i want div#a to do one thing when it is the subject of an ajax event and div#b to do something different. so, fundamentally, i want to be able to tell which div the load() was called upon when i catch an ajax event. i'm beginning to think it's not possible. perhaps i should take this up with jquery-dev...
Ok, i went ahead and looked at the jQuery ajax and event code. jQuery only ever triggers ajax events globally (without a target element):
jQuery.event.trigger("ajaxStart");
No other information goes along. :(
So, when the trigger method gets such call, it looks through jQuery.cache and finds all elements that have a handler bound for that event type and jQuery.event.trigger again, but this time with that element as the target.
So, it's exactly as it appears in the demo. When one actual ajax event occurs, jQuery triggers a non-bubbling event for every element to which a handler for that event is bound.
So, i suppose i have to lobby them to send more info along with that "ajaxStart" trigger when a load() call happens.
Update: Ariel committed support for this recently. It should be in jQuery 1.4 (or whatever they decide to call the next version).
when you set ajaxStart, it's going to go off for both divs. so when you set each div to react to the ajaxStart event, every time ajax starts, they will both go off...
you should do something separate for each click handler and something generic for your ajaxStart event...
Because you have a selector with two elements, you're creating two ajaxStart handlers. ajaxStart is a global event, so as soon as you fire any ajax event, the onajax function is going to be called twice. So yes, you'd get two popups.