Search code examples
javascriptgoogle-chrome-devtoolsdom-eventsjavascript-debugger

Javascript DOM-event origin and dependencies


Imagine that there's a button on one web page (not mine) and when it's clicked it performs some Javascript. I want to have a button on my web page that performs exactly the same. So I need to attach all necessary js files (but first I have to find them) to my html page and sometimes add some js to my html page.

What I usually do in this case? I inspect this button html element to see if there's onclick attribute for this button. If it is, I see the function called when button is clicked and then I try to search for this function in current html page and all js files attached to page. Also I need to find all dependencies (like jQuery, fancybox etc.).

If the button doesn't have onclick attribute I have to look for direct getElementById or jQuery selector pointing to this button with rest of code there. Sometimes there's no such a selector and I have to find a nested selector - really hard and annoying thing.

Is there any better, automated way for doing things above. Ideally after selecting the element in DOM (button in this case) and pressing some magic button I will be able to see all js files involved in processing this click and also js code in html page.


Solution

  • It's going to involve digging no matter what you do. But Chrome's Dev Tools can help with the attached event handlers, to an extent. When you right-click an element and inspect it, on the right-hand side there's a panel showing various tabs: [Styles] [Computed] [Event Listeners] [DOM Breakpoints] [Properties]. The [Event Listeners] one shows the listeners directly attached to that element. Of course, on a site using jQuery (which is more than half the sites using JavaScript at all), looking at the handler will dump you into the jQuery event handling code, but it's a start.


    Just as a side point: While it's fine to look at the source of pages for inspiration, or to see how they solved a particular problem, or what plugins they're using to get an effect, etc., I assume you're not grabbing large sections of their actual code (as opposed to libraries and plugins with liberal licenses) without their permission, which is probably not cool.