Reputation: 3162
I have search a lot but couldn't find proper solution. I am going to element prepend/append to another element after certain width. But it works after resize browser only.
I have found this solution but still not helpful
How can i achieve?
$(window).on("resize", function(event){
$vWidth = $(this).width();
$('#test').html($vWidth)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
Upvotes: 0
Views: 4284
Reputation: 4619
If you want the code to run when the page loads you can also have it triggered when the page is ready.
I would convert the relevant portion of your code into a function
to avoid duplication of codes.
Demo working sample:
https://jsfiddle.net/j6nermyL/9/
Sample JS code:
$(document).ready(function() {
checkWidth();
});
$(window).on("resize", function(){
checkWidth();
});
function checkWidth(){
$vWidth = $(window).width();
$('#test').html($vWidth);
//Check condition for screen width
if($vWidth < 700){
$('#msg').html("Width: Less than 700");
}else{
$('#msg').html("Width: More than 700");
}
}
Sample HTML code:
<div id="test">Test</div>
<br>
<div id="msg"></div>
$(window)
Reference:
Upvotes: 1
Reputation: 1572
Use load
, if you want to do action on page load
Try this:
$(window).on("resize", function(event){
$vWidth = $(this).width();
$('#test').html($vWidth)
});
$(window).on("load", function(event){
$vWidth = $(this).width();
$('#test').html($vWidth)
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="test"></div>
Upvotes: 0
Reputation: 2395
To make it work on Load, try
$( window ).load(function() {
// Run code
});
and on resize try
$(window).on("resize", function(event){
$vWidth = $(this).width();
$('#test').html($vWidth)
});
you can write the conditions like $(window).width() < 700
inside the methods
Upvotes: 2