How to fire an event immediately? - javascript

I'm binding an event like this, using prototype js:
$('country').observe('change',function(e) { ... });
How can I fire it once immediately?
in jQuery, I'd just tack on a .triggerHandler('change'). Is there something similar in prototype?

Use the load event. Something like this:
// calls addListeners when the document loads
Event.observe(window, 'load', addListeners, false);
function addListeners() {
// called onLoad
fireOnce();
// observer for the country dropdown
$('country').observe('change', function(event) {
fireOnChange();
});
}
function fireOnce() {
// do something
}
function fireOnChange() {
// do something
}
When the document loads, fireOnce() will execute. I use this technique all the time.

If using an extension is an option, I have had success in the past with event.simulate for this purpose.
It'll allow you to do something like:
$('country').simulate('change');

Try this:
var handler = function(e) {...};
$("country").observe("change",handler);
handler();
Alternatively (less readable, avoids temporary variable):
$("country").observe("change",(function(e) { ... return arguments.callee;})());
However, in both cases you will not be able to use this as you might expect. This solution is better suited to more general callbacks such as for setInterval

...if you know that it exists, and you know that you're not waiting for pageload or waiting for a script to load, why not just:
(function (el) {
if (!el) { return; }
doSomething(el);
}(document.getElementById("country")));

Related

How can I add an event for a one time click to a function?

I would like to add a click event listener to a function but would only like it to happen once. How could i do this?
I would like to stay clear of JQuery as well if it is possible please.
EDITED
As the answers that I am getting for this are fully satisfying my need i thought i may make it a bit more clear with context.
I am writing a function to draw a rectangle, first with one click on a button to initiate the rectangle function. Then there are two click event listeners in the drawRectangle function. These are the events i would like to happen only once in the function. Allowing the user to then create another rectangle if they click on the rectangle initiation button again.
Use modern JavaScript!
EventTarget.addEventListener("click", function() {
// Do something cool
}, {once : true});
A Boolean indicating that the listener should be invoked at most once after being added. If true, the listener would be automatically removed when invoked.
- MDN web docs
All modern browsers support this feature
Other reference
You have to use removeEventListener once the event is fired once. However, removeEventListener takes a function as argument, which means you need to declare a named function, add it with addEventListener, and have it removing itself. Example:
function foo() {
// do things, then
removeEventListener('click', foo);
}
addEventListener('click', foo);
function one(el, type, fn) {
function handler(event) {
el.removeEventListener(type, handler);
fn(event);
}
el.addEventListener(type, handler);
}
// use it like
one(window, 'resize', function () {
alert("This triggers just once");
});
Example: http://jsfiddle.net/6njpem7x/
The other answers are correct in that this can be achieved with a named function, but you don't need to declare the function separately. You can use a named function expression:
element.addEventListener("click", function handler(event) {
this.removeEventListener("click", handler);
// ...
});
An alternative, though less optimal, approach is to keep around a variable that keeps track whether the handler was executed:
var wasExecuted = false;
element.addEventListener("click", function(event) {
if (wasExecuted) {
return;
}
wasExecuted = true;
// ...
});
The variable needs to be declared outside the handler but within scope, so that its value persists across event triggers.
Combination of addEventListener and removeEventListener:
element.addEventListener("click", clickFunction);
function clickFunction(e) {
console.log("clicked");
element.removeEventListener("click", clickFunction);
}
jsFiddle
something like this
var el = document.getElementById('something');
el.addEventListener('click', doSomething);
function doSomething() {
el.removeEventListener('click', doSomething);
//code
}
Inside event handler you can use universal: e.target.removeEventListener(e.type, arguments.callee)
Or you can make special function for creating "one time" event listeners:
function oneTimeListener(node, type, callback) {
// create event
node.addEventListener(type, function(e) {
// remove event listener
e.target.removeEventListener(e.type, arguments.callee);
// call handler with original context
// as it happens with native addEventListener
return callback.call(this, e);
});
}
oneTimeListener(document.getElementById("myElement"), "click", myHandler);
You can set a cookie after first click:
document.cookie="click=1; expires=.......";
and add condition to listener - if cookie is set, you omit that.
Another simple solution which I'm using is to add a dummy class to the element to which we are listening so that it will not fire again.
const myButton = document.querySelector('#my-button:not(.init)');
myButton.addEventListener('click', (e) => {
e.preventDefault();
myButton.classList.add('init');
});

jquery change event callback

How to call a function once after change() event complete?
for example, something like this: ( I know jQuery Doesn't have callback method as default )
$('#element').change( function(){
// do something on change
// $('#milestonesSelect').multiselect({ minWidth: 120 , height : '200px' ,selectedList: 4 }).multiselectfilter();
// some animation calls ...
// ...
}, function(){
// do something after complete
alert('another codes has completed when i called');
}
);
Is it possible to call a single callback after all the codes on change method done, except call a complete callback for every functions on it?
I need to do something after the change event has completed
Shall I need to set order to methods in change handler?
You can probably make use of event bubbling and register a callback in the document.
$(document).on('change', '#element', function(){
console.log('after all callbacks')
});
Demo: Fiddle
I just spent some time exploring this myself, and decided to submit my answer to this question as well. This is not utilizing any of jQuery's deferred methods, which might be a better approach. I haven't explored them enough to have an opinion on the matter.
$("#element").change(function() {
handler().after(callBack($("#element").val()));
}
function handler() {
alert("Event handler");
}
function callBack(foo) {
alert(foo);
}
Demo: JSFiddle
If I understand your question correctly, this will execute code only one time after a change event is fired:
var changed = false;
$('#element').on('change', function() {
if ( !changed ) {
// do something on change
changed = true;
}
}
});

Automatic call of on-click function in jquery

I am looking to call a onclick function forcefully.
$('.checkbox-selector').click(function() {
});
$('.checkbox-selector1').click(function() {
});
When a control goes to the first function, the second function should be called automatically
i.e. onlick event is triggered.
function func1(e) {
// do stuff for selector
// run func2 too!
func2();
}
function func2(e) {
// do stuff for selector1
}
$('.checkbox-selector').click(func1);
$('.checkbox-selector1').click(func2);
Is this what you mean?
If so, make sure to look at the comments! They contain quite valuable information considering events and such.
You can replace func2(); with $('.checkbox-selector1').trigger('click'); to trigger the native event handler too! Using $('.checkbox-selector1').triggerHandler('click'); is practically the same as func2();, whichever you prefer.
Take a look at the jQuery trigger function
Not sure what it is exactly you're looking for, but I'd guess:
$('.checkbox-selector').click(function() {
/* all sorts of stuff*/
$('.checkbox-selector1').click();
//or:
$('.checkbox-selector1').trigger('click');
});
$('.checkbox-selector1').click(function() {
});
Something like that?

Clearing a jquery document.ready() call

How do I clear out anonymous functions that are set to trigger via a jQuery document.ready() call?
For example:
<script type="text/javascript">
//some code sets a doc ready callback
$(document).ready(function ()
{
alert('ready');
});
//my attempt to prevent the callback from happening
window.onload = null;
$(document).unbind("ready");
</script>
The alert happens regardless of my attempts to circumvent it. Is there any way to do this?
You'd probably get the most appropriate answer if you described what problem you're really trying to solve.
jQuery doesn't have a publicly documented way to undo or block document.ready() handlers. If you control the code, you can use a global variable and a conditional like this:
var skipReady = false;
$(document).ready(function ()
{
if (!skipReady) {
alert('ready');
}
});
// skip the document.ready code, if it hasn't already fired
skipReady = true;
Or, if you want to hack into jQuery a bit (beyond the documented interfaces), you can do this:
$(document).ready(function() {
alert("ready");
});
// stop the ready handler
$.isReady = true;
You can see this last one work here: http://jsfiddle.net/jfriend00/ZjH2k/. This works because jQuery uses the property: $.isReady to keep track of whether it has already fired the ready handlers or not. Setting it to true makes it think it has already fired them so it won't every do it again.
This works:
$(document).bind("ready", function () { alert("hey!"); });
$(document).unbind("ready");
Seems like a bug to me - all other events in jQuery are able to be unbound. Omitting this one is inconsistent.
Not a direct answer as to the omission, but here's some related info from jQuery docs:
All three of the following syntaxes are equivalent:
$(document).ready(handler)
$().ready(handler) (this is not recommended)
$(handler)
There is also $(document).bind("ready", handler). This behaves similarly to the ready method but with one exception: If the ready event has already fired and you try to .bind("ready") the bound handler will not be executed. Ready handlers bound this way are executed after any bound by the other three methods above.
$(document).ready() is dependent on the onLoad event which is triggered by the browser meaning you can not prevent it from happening. If the alert() is determined by some condition then I would use an if/else statement to decide whether it is called.
Super old question, but came across the need to do this recently to prevent document.ready code I didn't control from running in certain instances. This can be achieved by proxying jQuery's ready function, rather like a test spy. The following will work:
var ready = $.prototype.ready;
// proxy the ready function
$.prototype.ready = function ( fn, allowed ) {
allowed = allowed || false;
if ( allowed ) {
ready.call( this, fn );
}
};
All calls to $( document ).ready will now be ignored. You can override this behaviour by passing true as the second argument: $( document ).ready( fn, true )

How To Access jQuery Event Without Using Anonymous Callback Parameter

Typically, when needing to access an event, you do so via the parameter specified in the callback function:
$button.live("click", function(ev) {
// do something with ev here, like check 'ev.target'
}
But instead (for reasons too complicated to get into here), I do not want to use an anonymous callback function, but instead specify a function to call, like this:
$button.live("click", functionToCall(ev, $(this));
So you'll notice that I included 'ev' as a parameter to functionToCall(), but this obviously won't work because I'm not using the anonymous callback function. But I do still need to access that click event (to check ev.target) within functionToCall(). My question is, how do I access this event? It would be nice if I could do something like this:
$button.live("click", functionToCall($(this));
and
function functionToCall($item) {
var target = $item.event("click").target;
// do something with target
}
Any ideas would be very much appreciated. Thanks.
Original answer
function test(eve) {
alert(eve.type);
alert(this);
//$(this) if you need it as jQuery object
}
$([yourselector]).live("click", test);
You will automatically get the event in the eve parameter.
Answer to extended question in comment
Passing in a parameter makes it a little more difficult. If you need an explanation why I did it like this: Ask.
function helper(customparam) {
return function(eve, selector) { actualFunction(eve, selector, customparam, this) };
}
function actualFunction(eve, selector, customparam, self) {
alert(eve.type);
alert(selector);
alert(customparam);
alert(self); //self is now the element we clicked on
//$(self) if you need it as jQuery object
//using this won't work anymore as this is now window
}
$([yourselector]).live("click", helper([yourparameter]));
You could call a function within the anonymous callback function:
$button.live("click", function(ev) {
functionToCall(ev, $(this));
}
EDIT: I think this may be what you're looking to do (untested):
function handleClick(ev) {
$(this).die("click");
// ...whatever processing to do...
$(this).live("click", handleClick);
}
$button.live("click", handleClick);
I believe the $(this) will refer to the button object in which the function was called.
Remember that jQuery re-assigns this when it calls event handlers, by using the Function methods call or apply. So when functionToCall is invoked, this is the DOM element of $button.
var functionToCall(ev) {
var $this = $(this);
$this.die("click", functionToCall);
// stuff
$this.live("click", functionToCall);
}
$button.live("click", functionToCall);
var mythis = $(this);
var callback = function(ev) {
var target = mythis.event("click").target;
}
$button.live("click", callback);

Categories