Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

I created a somefile.js where somefile.js contains some jQuery method. So for instance it contains this function:

function showWindow(divID)
{
    var dialogDiv = $(divID);

    dialogDiv.dialog
    (
        {
            bgiframe: true,
            modal: true,
            autoOpen: false,
            show: 'blind'
        }
    )

    dialogDiv.dialog("open");
}

So in my .aspx page (or whatever, it could be an .html), I have a button:

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

My question is, we're going to use showPopUp all over in our app. If it's called from an onClick event, then where do I put my $(document).ready(function() since this code is not in the page, but in a .js file?

like image 891
PositiveGuy Avatar asked Apr 13 '10 15:04

PositiveGuy


2 Answers

You can put it in the Javascript file if you want. If you're attaching listeners with the onclick attribute like that, you don't actually need to use $(document).ready().

However, it's generally considered better form to not use the onclick attribute, and attach the listener in Javascript, like so:

<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 that javascript in the head of the document like ~ricebowl said.

like image 144
Quasipickle Avatar answered Oct 01 '22 23:10

Quasipickle


Put the $(document).ready(...); in the head of the (x)html page (or, indeed, .php, .aspx, etc) as normal, just so long as you make sure that it comes after the linked script file (to load your somefile.js) and, of course, the 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 note that I feel that I'm missing something obvious in your question. Please comment if I'm being completely obvious and missing your point...
like image 43
David Thomas Avatar answered Oct 02 '22 00:10

David Thomas