I’d like to be able to dynamically load an external javascript file, and then bind methods from the script to specific elements in the DOM. Is that possible? How? With what constraints?
I imagine a solution would look something like this, but I’m open to anything that will work:
<html><body>
<div class="A">aaaaa</div>
<div class="B">bbbbb</div>
<div class="A">aaa</div>
</body></html>
<script type="text/javascript">
//This is the internal script, part of the original page
$.get("url/outside_script.js",
function(script_obj){
$(".A").bind('niftyMethod', script_obj.niftyMethod)
}
);
</script>
Here’s the external script: outside_script.js
<script type="text/javascript">
var script_obj = {
niftyMethod : function(){
//Do cool stuff in the context of a DOM object.
$(this).fadeOut(500,function(){$(this).fadeIn(500)});
}
</script>
I’ve done a good bit of Googling on this, but haven’t found much. Maybe I’m using the wrong search terms…?
NB: I’m happy to use jquery if that’s what it takes.
Some corrections:
Script:
External file: