Reputation: 2050
I'm trying to center a div on my page using jquery and the core code works fine, it centers the div when the page is resized. However I need it resized for load, so I'm calling $(window).reize();
right after the custom code but for some reason it's only working if you resize the page, not when the page loads.
Here is the code:
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>TEST PAGE</title>
<link rel="stylesheet" type="text/css" href="style.css" >
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<script>
$(window).resize(function()
{
$('.mainContent').css({
position:'absolute',
left: ($(window).width() - $('.mainContent').outerWidth())/2,
top: ($(window).height() - $('.mainContent').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
</script>
<body>
<div class="mainContent">
This is a test
</div>
</body>
</html>
Upvotes: 0
Views: 185
Reputation: 122
I think there is a problem with your src attribute.If you are trying to reference an online script Just replace your src with (https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js) and then you can go ahead with ready function.I tried your code and it worked fine for me.
Upvotes: 1
Reputation: 122
Place the script in body tag and then proceed with ready function and check whether it's working or not?
Upvotes: 1
Reputation: 85545
You can just trigger the resize right after the ending like below:
$(window).resize(function()
{
$('.mainContent').css({
position:'absolute',
left: ($(window).width() - $('.mainContent').outerWidth())/2,
top: ($(window).height() - $('.mainContent').outerHeight())/2
});
}).resize();
Upvotes: 1
Reputation: 10378
use ready
set your code in $(document).ready
$(document).ready(function(){
$(window).resize(function()
{
$('.mainContent').css({
position:'absolute',
left: ($(window).width() - $('.mainContent').outerWidth())/2,
top: ($(window).height() - $('.mainContent').outerHeight())/2
});
});
// To initially run the function:
$(window).resize();
});
Upvotes: 1