Reputation: 79
I have the following script to set a height
on a div
containing a Google Map control:
<script>
var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
//alert("Height:" + height)
document.getElementById('divMap').setAttribute("style", "width:" + height);
</script>
Further down, the div
is defined:
<div id="divMap" class="col-md-6" style="min-height: 800px; height:100%">
<map:GoogleMap ID="GoogleMap1" runat="server" Width="100%" Height="100%">
</map:GoogleMap>
<map:GoogleMarkers ID="GoogleMarkers1" TargetControlID="GoogleMap1" runat="server" OnClick="GoogleMarkers1_Click" />
</div>
The script works wonderfully on load. I get the height
of the browser window.
However, getElementById()
always fails.
It's like the div
doesn't exist when the script runs. If I choose to debug the page, nothing more than the <script>
tags are shown.
I'm missing something, but what?
Or is there another way to set the height
of a div
in asp.net?
Upvotes: 1
Views: 1693
Reputation: 336
I believe this is because you load the script
tag first before loading the body. When the script
load first it will look for the element which does not exist yet in the body
. Therefore it cannot find the element. You need to put the script
at the bottom.
Like this:
<body>
<div id="divMap">
...
</div>
<script>
...
</script>
</body>
You need to let the element load first. So the element will exist in the body.
Upvotes: 1
Reputation: 67505
The error says that divMap
is not found null
or undefined
what means you script code can't be found in the DOM what means, in other words, the script tries to get the element when it's not loaded yet.
So to make sure all the DOM elements are loaded before the script runs you could add you code inside the ready function like :
document.addEventListener("DOMContentLoaded", function(event) {
//Your code here
});
NOTE: If you have the control over the page structure you could separate the JS from the HTML in the body, since mixing them isn't a good practise.
Upvotes: 1
Reputation: 1866
I think the issue is you are trying to access the div before it is in the DOM. Try this:
<html>
<head>
</head>
<body>
<div id="divMap" class="col-md-6" style="min-height: 800px; height:100%">
<map:GoogleMap ID="GoogleMap1" runat="server" Width="100%" Height="100%">
</map:GoogleMap>
<map:GoogleMarkers ID="GoogleMarkers1" TargetControlID="GoogleMap1" runat="server" OnClick="GoogleMarkers1_Click" />
</div>
<script>
(function() {
/var height = window.innerHeight ? window.innerHeight : document.documentElement.clientHeight ? document.documentElement.clientHeight : screen.height;
//alert("Height:" + height)
document.getElementById('divMap').setAttribute("style", "width:" + height);
})();
</script>
</body>
</html>
Upvotes: 1