asdqwe

How to get max width for div using jquery

I have 3 divs for example

<div id="d1" style="float:left;width:150px;"> asdqwe </div> <div id="d2" style="float:left;"> qwerty </div> <div id="d3" style="float:right;width:150px;"> poilkj </div> 

Now I want to dynamically set the width of the d2 div and set it to the maximum available with screen resolution using jquery.

I tried jQuery('#d2').width() but it only gives us the actual hold width.

I want to show the screen of my web page, for example, d1 for 150px on the left and d3 for 150px on the right and the rest is available widht for d2.

Please let me know how we do this ????

+4
source share
7 answers

By default, a <div> only fills the space needed to accommodate it.

You cannot get the width you need, but you can set it:

 $("#d2").width($(window).width() - $("#d1").width() - $("#d1").width); 

Be warned: if the user resizes his window (or anything else to resize the viewport), you will need to update this value. You can get around this by connecting to the window resize event:

 $(window).on("resize", function() { $("#d2").width($(window).width() - $("#d1").width() - $("#d1").width); }); 
+4
source
 entireScreenWidth = screen.width d1Width = $("#d1").width() d2Width = $("#d2").width() $("#d3").width(entireScreenWidth-d1Width-d2Width) 
+1
source

In your scenario, you need to get the width of the screen and subtract the width of # d1 and # d3 from the width of the screen. This calculated width can be assigned to # d2.

0
source

You can get the width of the viewport using

 var screenWidth = $( window ).width(); 

Then set the width for #d2 as:

 $('#d2').css('width', screenWidth - 300); 
0
source
 Math.max.apply(Math, $('#d2').map(function(){ return $(this).width(); }).get()); 

Under the assumption, I will break this:

 $('#d2').map(function(){ return $(this).width(); }).get(); 

Math.max takes N arguments, so you should call it like: Math.max (200, 300, 250, 100, 400), which makes the result of Math.max.apply.

0
source

you should try this

 $( document ).ready( function(){ setMaxWidth(); $( window ).bind( "resize", setMaxWidth ); //Remove this if it not needed. It will react when window changes size. function setMaxWidth() { $( "#d2" ).css( "maxWidth", ( $( window ).width() * 0.7 | 0 ) + "px" ); } }); 
0
source

Unless you just float the middle div and put the floats in the source code, you won't need Javascript, because the browser can handle this on its own.

 <div id="d1" style="float:left;width:150px;"> asdqwe </div> <div id="d3" style="float:right;width:150px;"> poilkj </div> <div id="d2"> qwerty </div> 

If you do not have requirements that you did not tell us about, this should do it.

0
source

Source: https://habr.com/ru/post/1502970/


All Articles