This repository has been archived by the owner on Nov 29, 2017. It is now read-only.
forked from muka/Simple-JavaScript-DOM-Inspector
-
Notifications
You must be signed in to change notification settings - Fork 4
/
inspector.js
343 lines (284 loc) · 9.22 KB
/
inspector.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
/**
* DomInspector
*
* Based on https://github.com/oldprojects/Simple-JavaScript-DOM-Inspector/ (see 'initialise.source.js').
*
* Usage: var options = {}; // See 'initialise' method for attributes.
* var inspector = new DomInspector(options);
*
* @param Object options Initialisaton object (see 'initialise' method).
* @return Object Public members.
*
* Notes: Requires jQuery.
*
* */
function DomInspector (options)
{
var escapeKeyCode = 27;
var options,
$document,
last,
inspecting,
path,
element;
/**
* Extracts the css path of the passed element.
*
* @param Element el DOM element to inspect (http://api.jquery.com/Types/#Element), passed via click handler event target (http://api.jquery.com/event.target/).
* @return string
*
* */
var cssPath = function (el)
{
element = el;
var fullPath = options.fullPath === true ? 1 : 0, // Set to 1 to build ultra-specific full CSS-path, or 0 for optimised selector
useNthChild = options.useNthChild === true ? 1 : 0, // Set to 1 to use ":nth-child()" pseudo-selectors to match the given element
cssPathStr = '',
testPath = '',
parents = [],
parentSelectors = [],
tagName,
cssId,
cssClass,
tagSelector,
vagueMatch,
nth,
i,
c;
while (el) { // Go up the list of parent nodes and build unique identifier for each.
vagueMatch = 0;
tagName = el.nodeName.toLowerCase(); // Get the node's HTML tag name in lowercase.
cssId = (el.id) ? ('#' + el.id) : false; // Get node's ID attribute, adding a '#'.
cssClass = (el.className) ? ('.' + el.className.replace(/\s+/g, ".")) : ''; // Get node's CSS classes, replacing spaces with '.'.
// Build a unique identifier for this parent node.
if (cssId) {
tagSelector = tagName + cssId + cssClass; // Matched by ID.
} else if (cssClass) {
tagSelector = tagName + cssClass; // Matched by class (will be checked for multiples afterwards).
} else {
vagueMatch = 1; // Couldn't match by ID or class, so use ":nth-child()" instead.
tagSelector = tagName;
}
tagSelector = tagSelector.replace(/\.+$/, ''); // Ensure selector doesn't end with a '.'.
parentSelectors.unshift(tagSelector); // Add this full tag selector to the parentSelectors array.
if (cssId && !fullPath) break; // If doing short/optimised CSS paths and this element has an ID, stop here.
el = el.parentNode !== document ? el.parentNode : false; // Go up to the next parent node.
}
// Build the CSS path string from the parent tag selectors.
for (i = 0; i < parentSelectors.length; i++) {
cssPathStr += ' ' + parentSelectors[i]; // + ' ' + cssPathStr;
// If using ":nth-child()" selectors and this selector has no ID / isn't the html or body tag...
if (useNthChild && !parentSelectors[i].match(/#/) && !parentSelectors[i].match(/^(html|body)$/)) {
// If there's no CSS class, or if the semi-complete CSS selector path matches multiple elements...
if (!parentSelectors[i].match(/\./) || $(cssPathStr).length > 1) {
// Count element's previous siblings for ":nth-child" pseudo-selector.
for (nth = 1,
c = el;
c !== null && c.previousElementSibling;
c = c.previousElementSibling,
nth++);
// Append ":nth-child()" to CSS path.
cssPathStr += ":nth-child(" + nth + ")";
}
}
}
return cssPathStr.replace(/^[ \t]+|[ \t]+$/, ''); // Return trimmed full CSS path.
};
/**
* Mouse over handler.
*
* @param Event event jQuery click mouseover event object (http://api.jquery.com/mouseover/).
* @return void
*
* */
var onMouseOver = function (e)
{
var element = e.target; // NB: This doesn't work in IE (needs fix).
element.style.outline = options.outline || '2px solid red'; // Set outline.
element.style.cursor = options.cursor || 'auto';
last = element; // Set last selected element so it can be 'deselected' on onKeyDown.
};
/**
* Mouse out handler.
*
* @param Event event jQuery click mouseout event object (http://api.jquery.com/mouseout/).
* @return void
*
* */
var onMouseOut = function (e)
{
e.target.style.outline = ''; // Remove outline from element.
e.target.style.cursor = 'auto';
};
/**
* Click handler.
*
* @param Event event jQuery click event object (https://api.jquery.com/click/).
* @return void
*
* */
var onClick = function (e)
{
e.preventDefault && e.preventDefault();
path = cssPath(e.target);
var $element = $(element);
var clickData = {
$element: $element,
url: $element && $element.length && $element.get(0).baseURI,
path: path,
event: e
};
var stoppable = options.onClick && options.onClick(clickData) !== false;
options.stopOnClick && stoppable && stopInspecting();
};
/**
* Key down handler.
*
* @param Event event jQuery keydown event object (https://api.jquery.com/keydown/).
* @return void
*
* */
var onKeyDown = function (e)
{
if (e.which === escapeKeyCode) {
options.stopOnEscape && stopInspecting();
}
options.onKeyDown && options.onKeyDown(e);
};
/**
* Starts the inspector.
*
* @throws "Document required" exception.
* @return void
*
* */
var startInspecting = function ()
{
if (!$document) {
throw "Document required.";
}
if (inspecting) {
return;
}
inspecting = true;
$document
.on('mouseover', onMouseOver)
.on('mouseout', onMouseOut)
.on('click', onClick);
if (options.keyContext || false) {
$(options.keyContext).on('keydown', onKeyDown);
} else {
$document.on('keyDown', onKeyDown);
}
};
/**
* Stops the inspector.
*
* @return void
*
* */
var stopInspecting = function ()
{
if (!inspecting) {
return;
}
inspecting = false;
$document
.off('mouseover', onMouseOver)
.off('mouseout', onMouseOut)
.off('click', onClick);
if (options.keyContext || false) {
$(options.keyContext).off('keydown', onKeyDown);
} else {
$document.off('keyDown', onKeyDown);
}
if (last && last.style) {
last.style.outline = 'none';
last.style.cursor = 'auto';
}
options.onStop && options.onStop();
};
/**
* Initialises the inspector.
*
* @param Object _options Initialisation object (underscored to avoid collisions with local 'options').
* @return void
*
* */
var initialise = function (_options)
{
stopInspecting();
$document = false,
last = false,
inspecting = false,
path = false,
element = false;
/**
* Merge passed options with defaults (listed below).
*
* */
options = $.extend(true, {
/**
* Contexts.
*
* */
document: document,
keyContext: document,
/**
* Booleans.
*
* */
fullPath: false,
useNthChild: true,
stopOnClick: false,
stopOnEscape: true,
startOnInitialise: true,
/**
* Mouse event styles.
*
* */
outline: '1px solid red',
cursor: 'pointer',
/**
* Events.
*
* */
onClick: function (data) {
console.log(data.path);
},
onStop: null,
onKeyDown: null,
}, _options || {});
/**
* If the document it passed, wrap it in a jQuery object.
*
* */
if (options.document || false) {
$document = $(options.document);
}
/**
* Unless instructed *not* to, start inspecting.
*
* */
if ($document) {
options.startOnInitialise && startInspecting();
}
};
/**
* Initialise the inspector with any instantiation options.
*
* */
initialise(options);
/**
* Public members.
*
* */
return {
initialise: initialise,
startInspecting: startInspecting,
stopInspecting: stopInspecting,
getPath: function () {
return path;
}
};
}