Marcel Marino
Marcel Marino

Reputation: 1002

jquery not selecting element from within js file

Here's what works:

<head>
<script type="text/javascript" src="scripts/jquery-ui-1.11.0.custom/jquery.min.js"></script>
<script type="text/javascript">
function getElemWidth(){
   var x =  $( "#menuDiv").width();
   alert(x);
}
</script>
</head>
<body onLoad="getElemWidth()" />
<div id="menuDiv" style="width:250px" />
</body>

Here's what doesn't work:

<head>
<script type="text/javascript" src="scripts/jquery-ui-1.11.0.custom/jquery.min.js"></script>
<script type="text/javascript" src="scripts/common.js"></script>
</head>
<body onLoad="getElemWidth()" />
<div id="menuDiv" style="width:250px" />
</body>

Contents of "common.js":

function getElemWidth(){
   var x =  $( "#menuDiv").width();
   alert(x);
}

It is calling the function in both cases. I can use jquery in both cases, for example:

x = $(window).width();

works just fine. For some reason I can't get the document elements from within the .js included file. Is there something I'm missing?

I even added this right below the "common.js" include:

<script type="text/javascript">
  $(document).ready(function(){
  alert($('#menuDiv').width());
  });
  </script>

That works perfectly fine. I can reference #menuDiv from within the same file that menuDiv appears, but not in an included javascript file. Is this normal?

Upvotes: 0

Views: 67

Answers (2)

thecodeparadox
thecodeparadox

Reputation: 87073

<head>
<script type="text/javascript" src="scripts/jquery-ui-1.11.0.custom/jquery.min.js"></script>
<script type="text/javascript" src="scripts/common.js"></script>
</script> <-- this is wrong, remove this extra tag

Depending on update question:

you should call the function within jQuery DOM ready

$(function (){
    getElemWidth();
});

and HTML should be

<head>
    <script type="text/javascript" src="scripts/jquery-ui-1.11.0.custom/jquery.min.js"></script>
    <script type="text/javascript" src="scripts/common.js"></script>
</head>
<body> <!-- remove onload -->
     <div id="menuDiv" style="width:250px" />
</body>

Upvotes: 1

Buggabill
Buggabill

Reputation: 13901

The problem is that the DOM is probably not ready for jQuery to act on it. The safest point at which to operate on the DOM is after the document is ready. The page may be loaded but not fully rendered. Your common.js should really look like this:

function getElemWidth(){
   var x =  $("#menuDiv").width();
   alert(x);
}

$(document).ready(function(){
    getElemWidth();
});

And your HTML like this:

<head>
    <script type="text/javascript" src="scripts/jquery-ui-1.11.0.custom/jquery.min.js"></script>
    <script type="text/javascript" src="scripts/common.js"></script>
</head>
<body>
    <div id="menuDiv" style="width:250px"></div>
</body>

Upvotes: 1

Related Questions