Reputation: 123
I have a jquery.
$(window).on('load resize', function() {
var dm3Width = $('.dm3').width()
$('.dm1').width(dm3Width);
});
Demo Here: https://jsfiddle.net/veusr0xn/
It changes dm1
, based on the width of dm3
. But it runs only after I adjusted the size of the window. How does it run as soon as the page loads?
Thank so much.
Upvotes: 2
Views: 122
Reputation: 1717
Define your query under $( document ).ready(function()
Scope so when document will load your query will automatically work
$( document ).ready(function() {
var width=$(".dm3").width();
$(".dm1").css('width',width);
$(window).resize(function() {
var dm3 = $('.dm3').width();
$(".dm1").css('width',dm3);
});
});
Upvotes: 5
Reputation: 143
Try this
$(window).on('resize',function() {
var dm3Width = $('.dm3').width() // Get dm3 width
$('.dm1').width(dm3Width); // Make dm1 width match dm3 width
});
$(document).ready(function() {
$(window).trigger('resize');
});
.dm3 {
width: 200px;
background: blue;
}
.dm1 {
background: green;
width: 100px;
}
@media only screen and (max-width: 400px) {
.dm3 {
width: 400px;
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dm3">
DM3
</div>
<div class="dm1">
DM1
</div>
Upvotes: 3
Reputation: 5620
There is no need for a script to deal with dimensions. CSS is mature enough to deal with practically every presentation aspects and a width is a rather basic rule to set.
Instead of dealing with it in Javascript (very inefficient), I recommend you to put both divs inside a container and set its width to 200px, then add @media rule to it. You will have exactly the same flexibility but won't be at the mercy of scripted looks.
HTML
<div class="dm">
<div class="dm3">
DM3
</div>
<div class="dm1">
DM1
</div>
</div>
CSS
.dm { width: 200px; }
.dm3 { background-color: blue; }
.dm1 { background-color: breen; }
@media only screen and (max-width: 400px) {
.dm {
width: 400px;
}
}
See it in action with this FIDDLE.
Upvotes: 5