views:

40

answers:

1

Hey all, This is more of a standards and structure question.

Consider this .load() scenario. I have a page that loads a second page into a div with the .load() function.

<html><head><title>My Page</title>

<script type='text/javascript' src='myfunctions.js'></script>

<head>

<body>
     <a href='#' id='click_link'>Click Me</a><br>
     <div id='target_container>
     </div>
</body>
</html>

Where myfunction.js holds a click routine, that when #click_link is clicked it loads a page into #target_container. Now the page being loaded also needs access to myfunction.js. I could load it again and this actually seems to work, or I could just put the javascript code that I need into the loaded page. This seems to work too.

My gripe, is that there has to be a better, more clean way of doing this. Am I going about this wrong? Or it this the only way to do this. I always thought javascript code should jailed inside <head></head> and be beaten viciously if it tried to live outside of it.

I saw several posts on this, but none have a clear explanation on if this is the best way to handle this problem.

Please let me know. ~ Thanks

+1  A: 

I think what you're looking for is jQuery's live() method. With it, you can bind events to all current and future elements with the particular selector. This means you can leave all the javascript in the head and not have to worry about binding and rebinding every time you add new elements into the DOM.

You can write something like this in myfunctions.js,

$('.new_or_old').live('mouseover', function(){
   myFunction();
});

and every element with the class 'new_or_old' will call myFunction() on mouseover, even if it's inserted after the original page load.

munch
Thanks munch... I'll have to give that a shot. If the page being loaded requires many methods, this may get convoluted really quick. There may not be a better way though. I can't really think of one, but I'm new to jQuery. My aim here is to reduce code and keep it clean and efficient.
cstrzelc
It may, but luckily you can keep the javascript for the loaded page in a separate file so it's easier to maintain and then either include it using another `<script>` tag or combine it with all the necessary js files into one and ship the single minified file out on the original page load
munch
btw if you want go into the deep of problem you can search google for "Event Delegation" and the traditional "Event Handling", this is a god read too http://robertnyman.com/2008/05/04/event-delegation-with-javascript/
aSeptik