I'm looking at an element that has several event handlers added to it the old-fashioned way--
<input onblur="doSomething()" onkeyup="doSomethingElse()">
When I check the event listeners panel in the inspector, it is entirely empty.
Is there a way to find the code for these in the page's source besides manually ctrl+f'ing for the function names?
You could use the toString method in your console:
doSomething.toString()
Or you could find it via the debugger:
function findMyCode(element){
debugger
element.onblur.call(element);
}
findMyCode(document.getElementById('idOfYourInput'));
Then step into the function call.
This is fixed in Chrome 70. Here's a screenshot of Chrome DevTools showing the registered event handlers for the selected input element,
And to find the source code for those function, just copy-paste the function name in the console, and press enter - you'll get the source code for those function.
Or, you can do a quick search by pressing Ctrl+Shift+F, which will open up the search panel. Now, check the regular expression box and type "function\s*doSomething\s*\(" and press Enter. This will take you directly to the function definition.
I'm trying to get the following code to work in all versions of IE, as it works find in other browsers:
Click Me
//Javascript
$(".specificClass").click(
function(e) {
e.preventDefault();
// Do Something
//return false; Doesn't work either
}
);
Switching to href="#" makes it try to go to the top of the page, again only in IE9. For example:
Leaving href="" redirects to the current link itself in IE9.
Click Me Two
It seems like both approaches triggers the onclick Javascript to be called, but the default behavior for href="" is not getting overridden. If I use event.preventDefault() nothing happens.
The below approach works:
Click Me Two
function doSomething(me) {
// event.preventDefault is not needed as the javascript is added via href
}
However I don't want to have href="javascript:" or onclick ="doSomething"for all my anchor tags just to get it to work in IE9.
I also don't want to use a different tag (tried the span tag for example) since it is tricky to style up in all browsers.
Any other ideas?
Looks like it is a legit bug, I have submitted a request to fix it. I have also put in a workaround for now:
https://connect.microsoft.com/IE/feedback/details/812247/event-preventdefault-or-return-false-dont-work-in-ie9
In IE9 the legacy event handler model is still partial used. preventDefault() works only, when the event listener is attached using addEventListener().
If you want to prevent default action from an inline handler, you have to use the legacy method:
event.returnValue = false;
event.cancelBubble = true; // This is affects like event.stopPropagation() in older IEs
Though jQuery not working is odd, I've no explanation for that... Unless you're running IE in compatible mode and use jQuery 2.X?
EDIT
Also a reference to console object will break the code in IE<10, if Dev Tools are not opened. You can find a lot of fixes for this problem at SO. My favorite is this:
// The very first lines in the global context
if (!window.console) {
window.console = {
log: function () {}
// Add other console methods, if the scripts on the page are using them
}
}
Though the console problem can be avoided with the code above, it's always better to remove all loggings from the final code to be published.
For IE9, if there is any console.log anywhere on the site, there will be unexpected behavior unless you have the developer tools open. Improbable for an actual user.
See how it works fine without any console.log (in IE9): jsfiddle.net/4hfjq/10, but not when you do: jsfiddle.net/4hfjq/20 tries to re-direct to "" page, unless you have the developer tool open.
In my case, there were just too many console.logs and so I go with another workaround, i.e. Use
Link and define that code without using JQuery .eventType approach. Check this: jsfiddle.net/4hfjq/22
This could be due to event bubbling.
See this link:
http://api.jquery.com/event.stopPropagation/
event.stopPropagation();
Is it possible to have multiple click events for the same element? I have tried to simply have it like so:
$('#templates').click(function(e) {
do something..
});
$('#templates').click(function(e) {
do something else also..
});
Yet only the second event fires. I cannot find any decent answers explaining how to do this for a singular element in an on-click?
Note: the first click event calls server-side and loads a new PHP template (this may have an effect on what I can use in the second call I guess, as individually both clicks work but the server call does not work if I try a second click for the same element)
$('#templates').click(function(e) {
functionOne();
functionTwo();
});
function functionOne(){
}
function functionTwo(){
}
perhaps?
Please check this fiddle:
http://jsfiddle.net/DqSSd/
As you can see it should work well.
So please provide more information, and it would be better, if you provide JS fiddle as well.
Because so far the problem might be in:
second event is fired before first event returns the result
first event returns error from the server
some of events contains syntax error
etc
You may check something of those with investigation of NET calls to server (with Firebug or Chrome Developer toolbar).
Also for testing purposes you can type in console $('#templates').data("events"), so you will be able to see all events and handlers for particular element.
I am a new programmer and still learning.
This is the code that I am trying to figure out:
<div id="buy" class="buy button">Buy</div>
When I click on the div (button), some JavaScript code is executed but I don't know were it is. How can I tell what function is fired when click happens? Some how a listener is attached to this element.
In Google chrome's developer tools (click the wrench icon >Tools>Developer tools), select the element in the Elements tab, on the right open the 'Event Listeners' panel you'll will see all events
If you use Firefox and Firebug you can try installing FireQuery. It will make it so you can see the handlers bound by jQuery. http://firequery.binaryage.com/
You can't do it in a really good manner by "just" using ECMAscript itself. For instance, if there was a click event handler added by DOM Level 1 in the form of
document.getElementById('buy').onclick = function() {};
you can of course easily intercept that property on the node itself. Things are getting more complicated if DOM Level 2 comes into play with .addEventListener() respectevily .attachEvent(). Now you don't really have a "place" to look for where all the different listener functions where bound from.
It gets better by using jQuery. jQuery will hold all it's event handler functions in a special object which is linked to the DOM node of invocation. You can check for that by getting the .data()-expando property for a node like
$('#buy').data('events');
However, now I already described three different ways of binding event listeners to a node (actually its two because a library like jQuery also uses DOM Level 1 or 2 methods of course).
It's really getting ugly if an event is triggerd by delegation. That means, we bound our click event on some parent-node just waiting for that event bubbling up to us so we can check the target. So now we don't even have a direct relationship between the node and the event listener.
Conclusion here is, lookout of a browser plugin or probably a thing like VisualEvent.
You may use "Visual Event 2" script as a bookmark or same script as Chrome extension.
This script shows all js events attached to dom-elements.
Use jQuery("#buy").data('events');
http://api.jquery.com/jQuery.data/ may be interesting.
Event handlers attached using traditional element.onclick= handler or HTML <element onclick="handler"> can be retrieved trivially from the element.onclick property from script or in-debugger.
Event handlers attached using DOM Level 2 Events addEventListener methods and IE's attachEvent cannot currently be retrieved from script at all. DOM Level 3 once proposed element.eventListenerList to get all listeners, but it is unclear whether this will make it to the final specification. There is no implementation in any browser today.
If you're using FireFox, you should have FireBug installed. Once you have that, you can install FireQuery, which will show you what jQuery events are bound to which objects.
http://getfirebug.com/
http://firequery.binaryage.com/
This is the easiest way I've found of how to do it:
http://www.sprymedia.co.uk/article/Visual+Event
When working with events in Javascript, it is often easy to lose track
of what events are subscribed where. This is particularly true if you
are using a large number of events, which is typical in a modern
interface employing progressive enhancement. Javascript libraries also
add another degree of complexity to listeners from a technical point
of view, while from a developers point of view they of course can make
life much easier! But when things go wrong it can be difficult to
trace down why this might be.
It is due to this I've put together a Javascript bookmarklet called
Visual Event which visually shows the elements on a page that have
events subscribed to them, what those events are and the function that
the event would run when triggered. This is primarily intended to
assist debugging, but it can also be very interesting and informative
to see the subscribed events on other pages.
There's a bookmark button there you can drag to your toolbar (FF or Chrome), then just click the button on any page where you want to see the events attached. Works great! (at least for events attached by jQuery or other libraries).
Are you using jQuery? If so, you want to search for one of these three lines of code:
$("#buy").click //the div is refered by its id
or
$(".buy").click //the div is refered to by the style "buy"
or
$(".button").click //refered to by the style "button"
Most newer browsers have "Developer Tools" built into them by pressing F12 (at least in IE and Chrome). That may help you do some further debugging and tracing.
Below is something I’ve used in the past that I think may be what you're looking for. What this does is watch a property on a page element (In the example below, it's the document's "Title" property) and then display an alert with the JS callstack whenever that property is changed. You’ll need to get this into the DOM before whatever code you're trying to find fires, but hopefully you’ll be able to identify what’s causing the problem.
I would recommend using Firefox and getting Firebug for JavaScript debugging.
// Call stack code
function showCallStack() {
var f=showCallStack,result="Call stack:\n";
while((f=f.caller)!==null) {
var sFunctionName = f.toString().match(/^function (\w+)\(/)
sFunctionName = (sFunctionName) ? sFunctionName[1] : 'anonymous function';
result += sFunctionName;
result += getArguments(f.toString(), f.arguments);
result += "\n";
}
alert(result);
}
function getArguments(sFunction, a) {
var i = sFunction.indexOf(' ');
var ii = sFunction.indexOf('(');
var iii = sFunction.indexOf(')');
var aArgs = sFunction.substr(ii+1, iii-ii-1).split(',')
var sArgs = '';
for(var i=0; i<a.length; i++) {
var q = ('string' == typeof a[i]) ? '"' : '';
sArgs+=((i>0) ? ', ' : '')+(typeof a[i])+' '+aArgs[i]+':'+q+a[i]+q+'';
}
return '('+sArgs+')';
}
var watchTitle = function(id, oldval, newval) { showCallStack(); }
// !! This is all you should need to update, setting it to whatever you want to watch.
document.watch("title", watchTitle);
Right-click page, and choose to view the page's source
Find <script> tags
Look for $("#buy") and something mentioning onClick or .on("click",function(){...});
If you can't find it, search for something along these lines: document.getElementById("buy")
You have found the function, or code, where the event handler code is
$("#buy") is JQuery's way of saying find an element that has an id attribute of buy and if it has a . following it with some function, that function is acting upon the element that was found by JQuery.
I have a link (a tag) which is given an onclick event and has dopostback enabled, when generated server-side.
To this link, I later bind a jquery click event.
The onclick event has return false; at the end of the function and the anonymouse function binded by jquery has return true;
When I click on the link the jquery function is run and the postback happens, but the code in the inline onclick event is not working.
I tried flipping around the return false and return true.
When the jquery function returns false, the code works in Chrome and FF, but not IE.
When the jquery function returns true, the code works in IE, but not in FF or Chrome.
I have also tried adding the inline code to the onmouseup event, but that does not help either.
Maybe I am missing something but why would one ever have jQuery do one thing with a bound event then have an onclick event on the element do another.
Just use jQuery to 2 both and don't forget to use e.preventDefault() as the first line of the function.
Post the relevant code and I will try to assist further.