I am try to catch form event in javascript
var event = window.event.srcElement;
This is working fine in IE, but in
Netscape/Firefox where event return undefined.
Can someone tel me how to catch event
in Netscape/Firefox?
IE and Netscape play different games.
But you can easily make it crossbrowser as such:
if (window.event) e = window.event;
var srcEl = e.srcElement? e.srcElement : e.target;
Use .target:
var event = event.target;
Or to check for both/fallback in a single statement:
function myHandler(event) {
var target = window.event.srcElement || event.target;
}
(In both cases... I'd rename your variable, since this isn't the actual event object, but an element.)
Related
OK, so there's a question that gets asked around here a lot about Firefox not responding to window.event, where instead you need to add an extra parameter to the function. I have no problems with that; my problem is how the heck do I do that if I want to assign the event listeners from within a different Javascript function?
Basically, what I'm trying to do is the common effect when you can have a form box that has grey text that would say, for example, "Your name..." and then when you click the box the text disappears and the color changes to black; unfocus with the box still empty and the prompt text will return.
Now, instead of coding this directly for every page I want to use it on, I'm trying to make a function that I can call with the ID of the form and it will automatically apply this to every input element. Here's the code:
function fadingForm(formElementID, endColor)
{
var form = document.getElementById(formElementID);
for(var i = 0; i < form.elements.length; i++)
{
form.elements[i].originalValue = form.elements[i].value;
form.elements[i].originalColor = form.elements[i].style.color;
form.elements[i].changedColor = endColor;
// Somehow I need to get that event parameter in here I guess?
// I tried just putting the variable event in as a parameter,
// but as you'd expect, that doesn't work.
form.elements[i].onfocus = function() { focused(); };
form.elements[i].onblur = function() { blurred(); };
}
}
function focused(e)
{
evt = e || window.event;
element = evt.target;
if(element.value == "" || element.value == element.originalValue)
{
element.value = "";
element.style.color = element.changedColor;
}
}
function blurred(e)
{
evt = e || window.event;
element = evt.target;
if(element.value == "" || element.value == element.originalValue)
{
element.value = element.originalValue;
element.style.color = element.originalColor;
}
}
And of course, this works perfectly in Chrome, Safari, etc...just not Firefox.
Your event listeners focused and blurred accept an event object e, but you never provide an event object. The event object that is provided to the anonymous wrapper functions is never used nor passed to focused/blurred. Thus, e is always undefined.
Instead, when you set up your listeners, do:
form.elements[i].onfocus = function(e) { focused(e); };
form.elements[i].onblur = function(e) { blurred(e); };
Or even:
form.elements[i].onfocus = focused;
form.elements[i].onblur = blurred;
So that the event object is passed directly into your listener functions.
I have the following event handler
document.addEventListener('keydown', handleBodyKeyDown, false);
HOW DO i prevent it from occurring when inside a input box
Within your handleBodyKeyDown function, check if
event.target.tagName.toUpperCase() == 'INPUT'
(or 'TEXTAREA').
Note: For older versions of IE, use event.srcElement.tagName.
Like so:
document.addEventListener('keydown', handleBodyKeyDown, false);
function handleBodyKeyDown(event)
{
var e = event || window.event,
target = e.target || e.srcElement;
if (target.tagName.toUpperCase() == 'INPUT') return;
// Now continue with your function
}
P.S. Why are you using addEventListener if you have jQuery on the page? In jQuery, all of this gets sorted out for you:
$(document).on('keydown', ':not(input)', function(e)
{
// Your code goes here...
});
In your handleBodyKeyDown method, check to see if the event originated on an input element:
function handleBodyKeyDown(event) {
if (event.target.tagName.toUpperCase() === 'INPUT') {
return; // do nothing
}
// do the rest of your code
}
Note that the toUpperCase call is necessary because the conditions that determine the case of the tagName property are quite complicated and sometimes all but uncontrollable.
See event.target at MDN.
If you are using jQuery you can try this which uses is() method to test the target element is input then do nothing.
function handleBodyKeyDown(event) {
if ($(event.target).is("input")) {
return;
}
else{
//Do your stuff here
}
}
This worked for me:
const fromInput = event => event.srcElement instanceof HTMLInputElement;
function handleBodyKeyDown(event) {
if(fromInput(event))
return;
// do your magic here
}
You could do something like:
handleBodyKeyDown = function(e) {
var e = e || window.event
if (e.target.tagName != "INPUT") {
// handle this since it isn't input
}
}
Sometimes (as to me) it is better not to prevent it to occur, but to ignore in the event cases, when it occured in the input. It's looks like this is also your case as well.
Just inspect evt.target || evt.srcElement property (modern frameworks do this normalization work for you, so, most probably this will be called target) whether it's input or not. If not, just ignore.
QuirksMode tells you how to get an event's target. You can check that it is not an input:
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
if( targ.tagName != "INPUT" ) {
//Perform your action here
}
}
Your question is tagged jQuery, in which case you can just test event.target as the framework normalizes this for you.
$(document).bind("keydown", function (event) {
if(event.target.tagName != "INPUT") {
//Do something
}
});
HandleBodyKeyDown function will be invoked in any case. You can not prevent its call on the method of recording as you indicated. You can only add a logic for checking if this an 'input' and return. Additionaly (if needed) you can prevent it from bubble up:
function handleBodyKeyDown(ev) {
ev=ev||event;
var sender=ev.target||ev.srcElement;
if(sender.tagName.toLowerCase()==="input") {
if(ev.stopPropagation)ev.stopPropagation();
else ev.cancelBubble=true; // for IE8 or less
return true; // do not prevent event from default action
}
// your code for global keydown
}
If you're using Prototype (which you have tagged but you also have two other frameworks tagged) then the event can be registered and filtered in one like this:
document.on('keydown', ':not(input)', handleBodyKeyDown);
I am trying to send the document and the control that the key was pressed in to the keypressed function.
Here is my code:
//Namespace
MyExt.BrowserOverlay = {
init: function() {
var appcontent = document.getElementById("appcontent"); // browser
if(appcontent)
appcontent.addEventListener("DOMContentLoaded", MyExt.BrowserOverlay.onPageLoad, true);
},
onPageLoad: function(aEvent) {
var doc = aEvent.originalTarget;
if (doc.location.href == "http://something.com"){
var txtBox = doc.getElementById('txtBox');
txtBox.addEventListener('keypress', keypressed, false); //Error Line
}
},
…
something like:
txtBox.addEventListener('keypress', keypressed(?,doc), false);
function keypressed(a,doc){
alert(a); //a relates to keypress
alert(doc.innerHTML);
}
Easiest way to pass variable is to attach it to Element that will trigger event, but you can access document by using global variable document.
As for event listeners, browsers handle events differently:
txtBox.someVar = "foobar"; // Any variable you want to pass
if(window.addEventListener){ // Firefox, Chrome...
txtBox.addEventListener('keypress', keypressed, false);
} else { // IE
txtBox.attachEvent('onkeypress', keypressed);
}
function keypressed(event){
// find event object
var e = event || window.event;
// find target object
var target = e.currentTarget;
if (e.target) target = e.target;
else if (e.srcElement) target = e.srcElement;
if (target.nodeType == 3) target = targ.parentNode;
// find key code
var code = e.charCode || e.keyCode;
alert(String.fromCharCode(code));
alert(target.someVar);
alert(document.body.innerHTML);
}
You can use gBrowser.contentDocument to get the document of the currently selected tab. See this article on the tabbed browser control for more info.
I need to have a handler on the calling object of onclick event.
link
<script>
function click123(event) {
//i need <a> so i can manipulate it with Jquery
}
</script>
I want to do this without the use of $().click or $().live of jQuery but with the method described above.
pass in this in the inline click handler
link
or use event.target in the function (according to the W3C DOM Level 2 Event model)
function click123(event)
{
var a = event.target;
}
But of course, IE is different, so the vanilla JavaScript way of handling this is
function doSomething(e) {
var targ;
if (!e) var e = window.event;
if (e.target) targ = e.target;
else if (e.srcElement) targ = e.srcElement;
if (targ.nodeType == 3) // defeat Safari bug
targ = targ.parentNode;
}
or less verbose
function doSomething(e) {
e = e || window.event;
var targ = e.target || e.srcElement || e;
if (targ.nodeType == 3) targ = targ.parentNode; // defeat Safari bug
}
where e is the event object that is passed to the function in browsers other than IE.
If you're using jQuery though, I would strongly encourage unobtrusive JavaScript and use jQuery to bind event handlers to elements.
I think the best way is to use currentTarget property instead of target property.
The currentTarget read-only property of the Event interface identifies the current target for the event, as the event traverses the DOM. It always refers to the element to which the event handler has been attached, as opposed to Event.target, which identifies the element on which the event occurred.
For example:
<span class="icon"></span> blah blah
Javascript:
a.addEventListener('click', e => {
e.currentTarget; // always returns "a" element
e.target; // may return "a" or "span"
})
The easiest way is to pass this to the click123 function or
you can also do something like this(cross-browser):
function click123(e){
e = e || window.event;
var src = e.target || e.srcElement;
//src element is the eventsource
}
http://docs.jquery.com/Events/jQuery.Event
Try with event.target
Contains the DOM element that issued
the event. This can be the element
that registered for the event or a
child of it.
The thing with your method is that you clutter your HTML with javascript. If you put your javascript in an external file you can access your HTML unobtrusive and this is much neater.
Lateron you can expand your code with addEventListener/attackEvent(IE) to prevent memory leaks.
This is without jQuery
link
window.onload = function () {
var el = document.getElementById('elementid');
el.onclick = function (e) {
var ev = e || window.event;
// here u can use this or el as the HTML node
}
}
You say you want to manipulate it with jQuery. So you can use jQuery. Than it is even better to do it like this:
// this is the window.onload startup of your JS as in my previous example. The difference is
// that you can add multiple onload functions
$(function () {
$('a#elementid').bind('click', function (e) {
// "this" points to the <a> element
// "e" points to the event object
});
});
Is this possible?
I am attempting to write a function for onmousedown that will return the ID of the element you just clicked for later use in recreating that element in a different div.
You can use event delegation, to basically connect only one event handler to your entire document, and get the element which the event was originally dispatched, using event.target:
document.body.onmousedown = function (e) {
e = e || window.event;
var elementId = (e.target || e.srcElement).id;
// call your re-create function
recreate(elementId);
// ...
}
function recreate (id) {
// you can do the DOM manipulation here.
}
Edit: You can assign events to all your Scriptaculous draggables in this way:
Event.observe(window, 'load', function () {
Draggables.drags.each(function (item) {
Event.observe(item.element, 'mousedown', function () {
alert('mouseDown ' + this.id); // the this variable is the element
}); // which has been "mouse downed"
});
});
Check an example here.
CMS pretty much has the correct answer but you will need to make it a little more cross browser friendly.
document.body.onmousedown = function (e) {
// Get IE event object
e = e || window.event;
// Get target in W3C browsers & IE
var elementId = e.target ? e.target.id : e.srcElement.id;
// ...
}
Pls insert this code to your javascript.
document.getElementById("article").onmouseup(handMu);
If you want to replicate the div id, an easy way might be cloneNode like this:
<div id="node1">
<span>ChildNode</span>
<span>ChildNode</span>
</div>
<div id="container"></div>
<script type="text/javascript">
var node1 = document.getElementById('node1');
var node2 = node1.cloneNode(true);
node2.setAttribute('id', 'node2');
var container = document.getElementById('container');
container.appendChild(node2);
</script>