Find script what sets button on focus - javascript

On a Drupal page a button element gets focused before the page has been loaded completely.
I'm trying to locate where this happens but unfortunately I wasn't able to track down the script. I'm using Chrome and tried to set a break-point but no luck. Further I tried to locate the line where this happens with the profiler. Also no luck so far. Do anyone know how to debug this properly? Any help is much appreciated. Thanks.
When I replace with a div, the issue is gone, so its related to the button element itself (no class nor element id)

What you want to do is right-click on the element you think is going to trigger the event and on the context menu click inspect. The chrome developer bar will open and you should see the html tag for that element you clicked on. On this bar there are two section: one with html tags and the others with tabs named Style, Computed, Event Listeners, DOM Breakpoints and Properties.
The one you want is Event Listeners, so click on that tab. Now we see all the listener for that html element grouped event type. When open a group you should see the list of element on left with a link to that specific line of code for the event handler. If you click on the link, you will be switch to the file where the code is.
Now the hard part. As you will see in some web pages, there are a lot of handlers. Also the use of libraries like JQuery make it harder to find the piece of code that really does something and the code is probably minified.
So let's supposed you found the code that you want to debug. Often it's in a format like
var namespace = {
...
handler: function(event) {
/* Event handler code here */
},
...
In a case like that, this might work
(function () {
var old_handler = namespace.handler;
namespace.handler = function () {
debugger; // this make a breakpoint here and stops
old_handler.apply(this, arguments);
}
})();
When all fails, make a local copy of the file that contains the code and setup an Apache server so that you proxy the web site except for that file which you will reference locally. Then you can modify it however you like. This won't work on https web site.

Related

How to Webstorm search references acquired by jquery selectors?

when you use ctrl+g on a reference, it finds you that within the same file
is there a more global search (all files in project) that finds direct references as well as as those places where jquery is invoked to get a reference to the object?
You can check the event that is occurring on any button or any html element when clicked.
All you need to do is instead of searching it right in the webstorm you can trace it accurately in the firebug.
Please make sure that firebug is installed or open the default developer's tool in your firefox or chrome browser.
To see the event that is occurring on an element :
right on the element and inspect it.
firebug will open up at the bottom of the browser and in the right-bottom corner you will find a box in which there are different tabs.
click on the events tab
you will see events such as click,mousehover....etc.
check the function that is getting called by clicking on that function name and it will show you the line of code that is being executed when you click that particular element with the js file name and the line number.
Hope that helps you out.

How to access the DOM after a previous JQuery call

I'm not too familiar with JQuery so please be patient.
Essentially, I have two hyperlinks on a view that runs some JQuery script:
Delete</td>
.
.
Undo
So, each of these links access different parts of the same .js file. My "Delete" does some processing which does a soft delete in the database. The DOM loads and this works fine. I'm using firebug and, when I insert a console.log in .js I can see the id of the Customer I want to delete and the rest is straight forward.
$(container).find('a.deleteCustomer:first').click(function(e) {
console.log("CustomerId " + $(container).find('input[name=Customer_CustomerId]:first').val());
My "Undo", however, accesses the same .js on a different line and console.log in the 'undo' part of .js reveals that it's not being hit.
$(container).find('a.undoCustomer').click(function(e) {
console.log("CustomerId " + $(container).find('input[name=Customer_CustomerId]:first').val());
So, it appears that the DOM is not ready (?). If this is the case, how do I fix this? Do I have to reload the DOM manually? If so, how?
P.S. When I click 'Undo' first nothing seems to happen i.e. I don't get any console.logs in FireBug. However, if I refresh the browser, it runs as expected i.e. the undo jquery about executes.
Without the full code, it is difficult to tell. From your post, title and comments, I see two possible causes.
First, you might be running your code before the DOM is fully ready, then try to wrap all your javascript initialization script in:
$(function() {
... // your code here
});
Second, are you deleting the "input" when you click on delete? If this is the case, it would be normal that "find" does not recover it. The solution to have an undo in such case would be to hide the "input" and show it back when clicking "undo".

jQuery & Chrome - Finding Button Hooks

Using Chrome's developer tools I am trying to determine what jQuery function is hooking an input button on the page for debugging purposes. I usually just keep searching until I find it, but I figured I'd ask this time.
Is there a way to find a jQuery button hook for a specific button in Chrome? I've tried looking through the Event Listener Breakpoints, but can never seem to find the right thing to pause it.
Basically, I need to know what jQuery / Javascript is being executed after the button is clicked.
The hooks are implemented in the application like so:
$('.button_class').click(function (){
$('#button_id').click(function(){
etc...
try this :
$(yourbutton).data('events');
Depending on the number of events/timers on the page this doesn't always work. But you can try "pausing" before clicking the button you want to debug in the JavaScript debug window. That way the debugger will pause on the next line that executes. The thing that occasionally prevents you from using that is if there is a "hover" or mouse move/in/out event tied on an element you have to pass over to get to the button (including the button itself). In that case I just remove those events (if I can) until I get the one I want. The event listener breakpoints would be more ideal but they're sometimes difficult when using jQuery or another library, I've actually put in a feature request to the Chrome Dev Tools team to address this very issue. (allowing you to specify what files are "yours" and only "breaking" in those specific files)
good luck -ck

Using Chrome, how to find to which events are bound to an element

Lets suppose I've a link on my page:
Click Here
I don't know anything else, but when I click on the link, an alert("bar") is displayed.
So I know that somewhere, some code is getting bound to #foo.
How can I find the code that is binding the alert("bar") to the click event?
I'm looking for a solution with Chrome.
Ps.: The example is fictive, so I'm not looking for solution like: "Use XXXXXX and search the whole project for "alert(\"bar\")". I want a real debugging/tracing solution.
Using Chrome 15.0.865.0 dev. There's an "Event Listeners" section on the Elements panel:
And an "Event Listeners Breakpoints" on the Scripts panel. Use a Mouse -> click breakpoint and then "step into next function call" while keeping an eye on the call stack to see what userland function handles the event. Ideally, you'd replace the minified version of jQuery with an unminified one so that you don't have to step in all the time, and use step over when possible.
You can also use Chrome's inspector to find attached events another way, as follows:
Right click on the element to inspect, or find it in the 'Elements' pane.
Then in the 'Event Listeners' tab/pane, expand the event (eg 'click')
Expand the various sub-nodes to find the one you want, and then look for where the 'handler' sub-node is.
Right click the word 'function', and then click 'Show function definition'
This will take you to where the handler was defined, as demonstrated in the following image, and explained by Paul Irish here: https://groups.google.com/forum/#!topic/google-chrome-developer-tools/NTcIS15uigA
Give it a try to the jQuery Audit extension (https://chrome.google.com/webstore/detail/jquery-audit/dhhnpbajdcgdmbbcoakfhmfgmemlncjg), after installing follow these steps:
Inspect the element
On the new 'jQuery Audit' tab expand the Events property
Choose for the Event you need
From the handler property, right click over function and select 'Show function definition'
You will now see the Event binding code
Click on the 'Pretty print' button for a more readable view of the code
(Latest as of 2022) For version Chrome Version Version 99:
Select the element you want to inspect
Choose the Event Listeners tab
Make sure to check the Framework listeners to show the real javascript file instead of the jquery function.
Edit: in lieu of my own answer, this one is quite excellent: How to debug JavaScript/jQuery event bindings with Firebug (or similar tool)
Google Chromes developer tools has a search function built into the scripts section
If you are unfamiliar with this tool: (just in case)
right click anywhere on a page (in chrome)
click 'Inspect Element'
click the 'Scripts' tab
Search bar in the top right
Doing a quick search for the #ID should take you to the binding function eventually.
Ex: searching for #foo would take you to
$('#foo').click(function(){ alert('bar'); })
2018 Update - Might be helpful for future readers:
I am not sure when this was originally introduced in Chrome. But another (easy) way this can be done now in Chrome is via console commands.
For example: (in chrome console type)
getEventListeners($0)
Whereas $0 is the selected element in the DOM.
https://developers.google.com/web/tools/chrome-devtools/console/command-line-reference#0_-_4
findEventHandlers is a jquery plugin, the raw code is here: https://raw.githubusercontent.com/ruidfigueiredo/findHandlersJS/master/findEventHandlers.js
Steps
Paste the raw code directely into chrome's console(note:must have jquery loaded already)
Use the following function call: findEventHandlers(eventType, selector);
to find the corresponding's selector specified element's eventType handler.
Example:
findEventHandlers("click", "#clickThis");
Then if any, the available event handler will show bellow, you need to expand to find the handler, right click the function and select show function definition
See: https://blinkingcaret.wordpress.com/2014/01/17/quickly-finding-and-debugging-jquery-event-handlers/
For Chrome Version 52.0.2743.116:
In Chrome's Developer Tools, bring up the 'Search' panel by hitting Ctrl+Shift+F.
Type in the name of the element you're trying to find.
Results for binded elements should appear in the panel and state the file they're located in.

Logging hyperlink clicks on my website

I have a website, where I allow other developers to host content.
My aim is to log clicks on every hyperlink (even the content that is hosted by other developers) ,which exists on the page.
My initial approach was as follows:
$('a').click(function(event)
{
//do my logging
return true;
}
);
Now with the above approach , I am facing the following issues:
Developers may have images inside the anchor link, so the events target is an image rather than href
Many developers have their own way of handling an href click , using an onclick event rather than a simply href='' attr
Some developers add their custom attr , to the tag, and have custom functions to handle the clicks
so basically , the issue is , there is a huge variety of anchor tags available, and logging clicks is not as simple.
Many cases allowed me to log the data I wanted, but a few cases , broke the code badly.
My aim to post on this forum was:
to discuss what is the right approach to do hyperlink clicks logging in a dynamic environment
is there a plugin out there , which allows a functionality like this.
I know facebook and google have this , but they have a totol control, on what is being hosted in their environments.
Any help is greatly appreciated.
Adding a click handler to every link is not a good idea. You should make use of event delegation (which will only attach one event handler at the root of the document):
$(document).delegate('a', 'click', function(event) {
// logging
});
Update (17.12.2011):
Since jQuery 1.7, one would use .on() [docs]:
$(document).on('click', 'a', function(event) {
// logging
});
Regarding your problems:
Developers may have images inside the anchor link, so the events target is an image rather than href
Events bubble up as long as propagation is not canceled. It depends on what you want to log. With delegate the event.target property will point to the image, but this (inside the handler) will point to the a element.
So you should have no problems here (example: http://jsfiddle.net/cR4DE/).
But that also means to you will miss clicks if the developers cancel the propagation.
(Side note: You could solve this letting the event handler fire in the capturing phase, but IE does not support this (hence jQuery does not either).)
Many developers have their own way of handling an href click , using an onclick event rather than a simply href='' attr
This will not touch existing event handlers.
Some developers add their custom attr , to the tag, and have custom functions to handle the clicks
Not sure what you mean here.
It also depends on how the other content is included. E.g. the above code won't track clicks in iframes.
In your logging code you should check for the bad cases and deal accordingly.
For example in your first case i you get the image and walk the dom up until i would find an a tag and log the href from there.
There will be some cases in which you will not be able to do the logging but if they are small compared with the cases you can do that you will be fine :).

Categories