Reputation: 9437
I have some jQuery code to dynamically check the screen size, it goes something like this...
$(window).resize(function() {
windowsize2 = $(window).height();
windowW = $(window).width();
if (windowsize2 < 400) {
...
...
The purpose of the code is to resize a particular div when the screen is made smaller. This works, but only when the screen is greater than 400
and then is shrunk down to below 400
.
However, let's say the user opens my website with a screen size of < 400
, in that case, the code above does not read the screen size and therefore does not resize the div. It will only do so if the user resizes the screen.
How can I use jQuery to ensure the div is resized if the user opens my website with a screen height of < 400
?
Upvotes: 2
Views: 308
Reputation: 35501
How can I use jQuery to ensure the div is resized if the user opens my website with a screen height of < 400?
You can refactor your code into a method and call that method on both resize and once the page is loaded.
Refactor your code into something like:
function resizeDiv() {
windowsize2 = $(window).height();
windowW = $(window).width();
if (windowsize2 < 400) {
...
...
}
Then, depending on your use case, there are two options to call a method when a page loads:
1. You can use document.ready:
$( document ).ready(function() {
resizeDiv();
});
Code included inside $(document).ready()
will only run once the DOM is ready for JavaScript code to execute.
2. you can use window.load
Code included inside $( window ).load()
will run once the entire page (images or iframes), not just the DOM, is ready.
$( window ).load(function() {
resizeDiv();
});
In general, it is not necessary to wait for all images to be fully loaded. If code can be executed earlier, it is usually best to place it in a handler sent to the ready()
method.
Upvotes: 1
Reputation: 16223
You could use .on()
to attach an event handler so your function runs on both window load and resize, thus making sure it works in either scenario:
$(window).on('load resize', function() {
windowsize2 = $(window).height();
windowW = $(window).width();
if (windowsize2 < 400) {
alert(1); // or whatever
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Upvotes: 1