Is that possible to know where is a jQuery function launched from ?
<div>
<script language="javascript">
$(document).ready(function () {
whereAmI($(currentDIV));
});
</script>
</div>
Is that possible to know where is a jQuery function launched from ?
<div>
<script language="javascript">
$(document).ready(function () {
whereAmI($(currentDIV));
});
</script>
</div>
If the function is being called by some sort of event, the first parameter is the Event object and you can just write something like.
$('a').click(function(e){
console.log(e.target);
});
There is nothing saved for you about the DOM location whence the currently executing JavaScript was loaded. However, you can use the fact that scripts are executed as they are loaded to achieve this memory:
<div id="target">
<script>
var thisScript1 = $('script').filter(':last');
$(document).ready(function () {
console.log(thisScript1.closest('div').attr('id')); // prints 'target'
});
</script>
</div>
<div id="second">
<script>
var thisScript2 = $('script').filter(':last');
$(document).ready(function () {
console.log(thisScript2.closest('div').attr('id')); // prints 'second'
});
</script>
</div>
Here, $('script').filter(':last');
refers to the last script element on the page, which at the time of execution is the "current script". Note that for each script I want to remember, I've named the variable housing the script object differently, otherwise it will be clobbered by subsequent scripts. An alternative would be to wrap each script in an immediately executed anonymous function, for the luxury of binding a local thisScript
variable.