Where to put my $ (document) .ready (function () {When I have methods in .js

I created somefile.js file where somefile.js contains some jQuery method. So, for example, it contains this function:

function showWindow(divID) { var dialogDiv = $(divID); dialogDiv.dialog ( { bgiframe: true, modal: true, autoOpen: false, show: 'blind' } ) dialogDiv.dialog("open"); } 

So on my .aspx page (or something else, it could be .html), I have a button:

 <input type="button" onclick="showPopUp('testDiv')" value="Click Me!" /> 

My question is: we are going to use showPopUp in our application. If it is called from the onClick event, then where do I put my $ (document) .ready (function (), since this code is not on the page, but in the .js file?

+7
jquery
source share
4 answers

You can put it in a Javascript file if you want. If you connect listeners with this onclick attribute, you actually don't need to use $ (document) .ready ().

However, it is generally believed that it is better not to use the onclick attribute and attach the listener in Javascript, for example:

<input type = "button" class = "showPopup" id = "testDiv" value = "Click Me!" />

 $(document).ready(function(){ $("input.showPopup").click(function(){ showWindow($(this).id); } function showWindow(id){...} } 

You can put this javascript at the top of the document, as the rice cooker said.

+4
source share

Put $(document).ready(...); in head (x) the html page (or, indeed, .php, .aspx, etc.) as usual, only until you make sure that it appears after the associated script file (load your file somefile.js ) and, of course, a link to your jQuery:

 <head> ... <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="somefile.js"></script> <script> $(document).ready( function() { $('input[type=button]').click().showPopUp('testDiv'); } ) </script> </head> 


Edited to notice that I feel that something obvious is missing from your question. Please comment if I am completely obvious and miss your point ...
+5
source share

The β€œcorrect” technical answer will depend on the structure (PHP, ASP.NET, etc.). If you want to use this function throughout the application, you can use the script tag:

 <script type="javascript" src="somefile.js" /> 

This tag can be included in the "page title", implemented in any way. For example, in ASP.NET I would include this tag in the main page.

0
source share

You need to do this: divide the function into two parts:

MakeDialog (divID) // this way you prepare the div for the dialog and ShowDialog (divID) // here you show the dialog

 //document load $(document).ready(function(){ MakeDialog(divId);//prepa }); function makeDialog(divID) { var dialogDiv = $(divID); dialogDiv.dialog ( { bgiframe: true, modal: true, autoOpen: false, show: 'blind' } ) } function showWindow(divId) { dialogDiv.dialog("open"); } 

NTN

0
source share

All Articles