Javascript manually firing .onchange() event - javascript

I have an input field I want to assign a new value and fire an .onchange() event. I did the following:
document.getElementById("range").value='500';
document.getElementById("range").onchange();
Where range is my input Id.
I get the following error:
Uncaught TypeError: Cannot read property 'target' of undefined
Is there a way to define the 'target'?
Thank you

Try using fireEvent or dispatchEvent (depending on browser) to raise the event:
document.getElementById("range").value='500';
if (document.getElementById("range").fireEvent) {
document.getElementById("range").fireEvent("onclick");
} else if (document.getElementById("range").dispatchEvent) {
var clickevent=document.createEvent("MouseEvents");
clickevent.initEvent("click", true, true);
document.getElementById("range").dispatchEvent(clickevent);
}

The error about target is because there's code in the event handler that's trying to read the target property of the Event object associated with the change event. You could try passing in an faux-Event to fool it:
var range= document.getElementById('range');
range.onchange({target: range});
or, if you can, change the handler code to use this instead of event.target. Unless you are using delegation (catching change events on child object from a parent, something that is troublesome for change events because IE doesn't ‘bubble’ them), the target of the change event is always going to be the element the event handler was registered on, making event.target redundant.
If the event handler uses more properties of Event than just target you would need to fake more, or go for the ‘real’ browser interface to dispatching events. This will also be necessary if event listeners might be in use (addEventListener, or attachEvent in IE) as they won't be visible on the direct onchange property. This is browser-dependent (fireEvent for IE, dispatchEvent for standards) and not available on older or more obscure browsers.

from : http://www.mail-archive.com/jquery-en#googlegroups.com/msg44887.html
Sometimes it's needed to create an
event programmatically. (Which is
different from running an event
function (triggering)
This can be done by the following fire
code
> var el=document.getElementById("ID1")
>
> fire(el,'change')
>
>
> function fire(evttype) {
> if (document.createEvent) {
> var evt = document.createEvent('HTMLEvents');
> evt.initEvent( evttype, false, false);
> el.dispatchEvent(evt);
> } else if (document.createEventObject) {
> el.fireEvent('on' + evttype);
> } } looks like this trick is not yet in jQuery, perhaps for a
> reason?

Generally, your code should work fine. There might be something else that's issuing the problem, though.
Where do you run those two lines?
Are you sure that the element with the
range id is loaded by the time you
run the code (e.g. you run it in
document.ready).
Are you sure that
you only have one element with id
range on the page?
What is your onchange() function doing (could be
helpful to post it here)?
Apart from that, I would recommend using jQuery (if possible):
$('#range').trigger('change');
or just
$('#range').change();
http://api.jquery.com/change/
But as I mentioned, your case should work fine too: http://jehiah.cz/a/firing-javascript-events-properly

This seems to work for me (see this fiddle). Do you have any other code that may be the problem? How did you define your onchange handler?
Are you calling e.target in your onchange handler? I suspect this may be the issue... since you are doing the change programmatically, there is no corresponding window event.

Related

efficient way to dynamically attach blur/focusout event to existing and any new input fields [duplicate]

I'm writing a form validation script and would like to validate a given field when its onblur event fires. I would also like to use event bubbling so i don't have to attach an onblur event to each individual form field. Unfortunately, the onblur event doesn't bubble. Just wondering if anyone knows of an elegant solution that can produce the same effect.
You're going to need to use event capturing (as opposed to bubbling) for standards-compliant browsers and focusout for IE:
if (myForm.addEventListener) {
// Standards browsers can use event Capturing. NOTE: capturing
// is triggered by virtue of setting the last parameter to true
myForm.addEventListener('blur', validationFunction, true);
}
else {
// IE can use its proprietary focusout event, which
// bubbles in the way you wish blur to:
myForm.onfocusout = validationFunction;
}
// And of course detect the element that blurred in your handler:
function validationFunction(e) {
var target = e ? e.target : window.event.srcElement;
// ...
}
See http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html for the juicy details
use 'Focusout' event as it has Bubble up effect..thanks.
ppk has a technique for this, including the necessary workarounds for IE: http://www.quirksmode.org/blog/archives/2008/04/delegating_the.html
aa, you can simply add the onblur event on the form, and will call the validation every time you change focus on any of the elements inside it

Change the Attr and do new function not working in jQuery [duplicate]

I have a site that uses AJAX to navigate. I have two pages that I use a click and drag feature using:
$(".myDragArea").mousedown(function(){
do stuff...
mouseDrag = true; // mouseDrag is global.
});
$("body").mousemove(function(){
if (mouseDrag) {
do stuff...
}
});
$("body").mouseup(function(){
if (mouseDrag) {
do stuff...
mouseDrag = false;
}
});
I just type that out, so excuse any incidental syntax errors. Two parts of the site use almost identical code, with the only difference being what is inside the $("body").mouseup() function. However, if I access the first part, then navigate to the second part, the code that runs on mouseup doesn't change. I have stepped through the code with Firebug, and no errors or thrown when $("body").mouseup() is run when the second part loads.
So, why doesn't the event handler change when I run $("body").mouseup() the second time?
Using $("body").mouseup( ... ) will add an event handler for the body that is triggered at mouseup.
If you want to add another event handler that would conflict with current event handler(s) then you must first remove the current conflicting event handler(s).
You have 4 options to do this with .unbind(). I'll list them from the least precise to the most precise options:
Nuclear option - Remove all event handlers from the body
$("body").unbind();
This is pretty crude. Let's try to improve.
The elephant gun - Remove all mouseup event handlers from the body
$("body").unbind('mouseup');
This is a little better, but we can still be more precise.
The surgeon's scalpel - Remove one specific event handler from the body
$("body").unbind('mouseup', myMouseUpV1);
Of course for this version you must set a variable to your event handler. In your case this would look something like:
myMouseUpV1 = function(){
if (mouseDrag) {
do stuff...
mouseDrag = false;
}
}
$("body").mouseup(myMouseUpV1);
$("body").unbind('mouseup', myMouseUpV1);
$("body").mouseup(myMouseUpV2); // where you've defined V2 somewhere
Scalpel with anesthesia (ok, the analogy's wearing thin) - You can create namespaces for the event handlers you bind and unbind. You can use this technique to bind and unbind either anonymous functions or references to functions. For namespaces, you have to use the .bind() method directly instead of one of the shortcuts ( like .mouseover() ).
To create a namespace:
$("body").bind('mouseup.mySpace', function() { ... });
or
$("body").bind('mouseup.mySpace', myHandler);
Then to unbind either of the previous examples, you would use:
$("body").unbind('mouseup.mySpace');
You can unbind multiple namespaced handlers at once by chaining them:
$("body").unbind('mouseup.mySpace1.mySpace2.yourSpace');
Finally, you can unbind all event handlers in a namespace irrespective of the event type!
$("body").unbind('.mySpace')
You cannot do this with a simple reference to a handler. $("body").unbind(myHandler) will not work, since with a simple reference to a handler you must specify the event type ( $("body").unbind('mouseup', myHandler) )!
PS: You can also unbind an event from within itself using .unbind(event). This could be useful if you want to trigger an event handler only a limited number of times.
var timesClicked = 0;
$('input').bind('click', function(event) {
alert('Moar Cheezburgerz!');
timesClicked++;
if (timesClicked >= 2) {
$('input').unbind(event);
$('input').val("NO MOAR!");
}
});​
Calling $("body").mouseup(function) will add an event handler.
You need to remove the existing handler by writing $("body").unbind('mouseup');.
jQUery doesn't "replace" event handlers when you wire up handlers.
If you're using Ajax to navigate, and not refreshing the overall DOM (i.e. not creating an entirely new body element on each request), then executing a new line like:
$("body").mouseup(function(){
is just going to add an additional handler. Your first handler will still exist.
You'll need to specifically remove any handlers by calling
$("body").unbind("mouseUp");

Simulate click in javascript [duplicate]

I want to simulate a click on any link on a page using JavaScript. If that link has some function binded to its 'onclick' event (by any other JS I don't have any control over), then that function must be called otherwise the link should behave in the normal manner and open a new page.
I am not sure that just checking the value of the 'onclick' handler would suffice. I want to build this so that it works on any link element.
I have no control over what function maybe binded to the onclick event of the link using whichever JS library (not necessarily jQuery) or by simply using JavaScript.
EDIT: With the help of the answers below, it looks like it is possible to check for event handlers attached using jQuery or using the onclick attribute. How do I check for event handlers attached using addEventListener / any other JS library so that it is foolproof?
You can use the the click function to trigger the click event on the selected element.
Example:
$( 'selector for your link' ).click ();
You can learn about various selectors in jQuery's documentation.
EDIT: like the commenters below have said; this only works on events attached with jQuery, inline or in the style of "element.onclick". It does not work with addEventListener, and it will not follow the link if no event handlers are defined.
You could solve this with something like this:
var linkEl = $( 'link selector' );
if ( linkEl.attr ( 'onclick' ) === undefined ) {
document.location = linkEl.attr ( 'href' );
} else {
linkEl.click ();
}
Don't know about addEventListener though.
Why not just the good ol' javascript?
$('#element')[0].click()
Just
$("#your_item").trigger("click");
using .trigger() you can simulate many type of events, just passing it as the parameter.
Easy! Just use jQuery's click function:
$("#theElement").click();
Try this
function submitRequest(buttonId) {
if (document.getElementById(buttonId) == null
|| document.getElementById(buttonId) == undefined) {
return;
}
if (document.getElementById(buttonId).dispatchEvent) {
var e = document.createEvent("MouseEvents");
e.initEvent("click", true, true);
document.getElementById(buttonId).dispatchEvent(e);
} else {
document.getElementById(buttonId).click();
}
}
and you can use it like
submitRequest("target-element-id");
At first see this question to see how you can find if a link has a jQuery handler assigned to it.
Next use:
$("a").attr("onclick")
to see if there is a javascript event assigned to it.
If any of the above is true, then call the click method. If not, get the link:
$("a").attr("href")
and follow it.
I am afraid I don't know what to do if addEventListener is used to add an event handler. If you are in charge of the full page source, use only jQuery event handlers.
All this might not help say when you use rails remote form button to simulate click to. I tried to port nice event simulation from prototype here: my snippets. Just did it and it works for me.

Javascript: Global Element Focus Listener

I am trying to set a listener that listens for all focus events. In particular I am trying to listen for anytime an input or textbox gains focus. Per some research, the widely accepted way to achieve this is like this:
document.body.onfocus = function(event) {
//Check the event.target for input/textbox
//Do something
};
But the document.body.onfocus doesn't seem to fire, ever. I thought it might be because the document doesn't actually ever receive focus so I tried:
document.body.focus();
To initially "set" the focus, but this doesn't work either.
Any ideas on how I can listen to a focus event on all inputs/textboxes without actually setting the event directly on the element itself? Vanilla javascript only please, I am not using a framework.
Per the accepted answer here is some working code:
var focusHandler = function(event) {
var type = event.target.nodeName.toLowerCase();
if(type == 'input' || type == 'textarea') {
//Do something
}
};
document.body.addEventListener('focus', focusHandler, true); //Non-IE
document.body.onfocusin = focusHandler; //IE
As some events (focus, blur, change) do not bubble up, I would recommend you to try Event Capturing instead. First of all onfocus will not work for this, so you have to use addEventListener where you are able to specifiy the used delegation mode in the third argument. Look at MDN for the use of addEventListener.
And take a look at this article for further information about delegating the focus event up.
The focus event doesn't bubble from elements up to their ancestor elements, so you can't use event delegation (hooking it on body and seeing it for all descendants of body) to detect it.
There's a newer event, focusin (a Microsoft innovation, now also available in other browsers), which does bubble, so that may work for you depending on which browsers you want to support.

javascript img src for any image on the page

I'm a JS newbie - still learning. I'm looking for a solution similar to this example
for displaying the source link of an image in an alert using onclick. However, I want to apply it to any image on the page, and there are no ID's on any of the images. Perhaps this is an application of the mysterious 'this'? Can anyone help me? Thanks!
No, this has to do with delegate event listeners, and the way events spread across the DOM.
When you click on an element in the page, a click event is generated. For what it matters to your purposes, this event is fired on the element, and it's caught by the function you define with onclick.
But the event also "bubbles up" to the parent, and it's caught by the onclick function defined there, if any. And then to the parent of the parent, and so on.
What you have to do, now, is to catch the event on the root element, which is the document object itself, or maybe the document.body element if you still want to use onclick (which is deprecated).
The event object is passed to the onclick function and it contains the original element that fired the event:
document.body.onclick = function(e) {
var tgt = e.target || e.srcElement;
if (tgt.tagName === "IMG")
alert(tgt.src);
}
(The e.target || e.srcElement part is because in IE<9 the target property is called srcElement.) That's the way you define a delegate event listener. It's not defined on the <img> elements, as you can see, but on their common ancestor.
But since you can define just one click event listener in the traditional way, I'd strongly recommend to use something more modern like the addEventListener method, which lets you add multiple event listeners on the same element for the same event type:
document.body.addEventListener("click", function(e) {
...
});
In Internet Explorer <9 you'll have to use attachEvent, which is quite similar but not the same. For a cross-browser solution, use a common JS framework like jQuery, or Prototype, or whatever.
If I understand your question this is your solution,
var img = document.getElementsByTagName('img');
for(var i=0;i<img.length;i++){
alert(img[i].src);
}

Categories

Resources