$ (window) .resize () and $ (document) .ready () compute different values

I am trying to make the text responsive using jQuery. Here is the fiddle:

http://jsfiddle.net/bq2ca7ch/

You can see the div with some text in it. The div does not have a given height, and the height is calculated from the height of the text and 10% paddings above and below.

I want the font size to be responsive. Let's say the size of the original div is 124px and the font size is 50 pixels, so I want to keep this ratio. This means that I need to know what percentage of 50 is from 124. This is about 40.32 (50/124 * 100). This means that I need to set the font size to a value equal to the height of the container / 100 * 40.32. Here is the code I used:

function foo(){ var container = $(".box"); var containerHeight = $(".box").innerHeight().toFixed(); var neededSize = (containerHeight/100*40.32).toFixed(); container.css("font-size", neededSize + "px"); } $(window).resize(foo); $(document).ready(foo); 

This seems to work, but only when resizing the page. When I reload it, there is a different meaning. Why does the same function give different values ​​when resizing and onload?

+5
source share
2 answers

What I noticed is that the size changes because:

1. When you just reboot. The function runs only once.

2. But when you resize, the function runs twice and resizes the font, because the recalculation is based on the new height. Most importantly, resizing is not calculated correctly innerheight

See this:

 function foo(jQuery ){ var container = $(".box"); var containerHeight = $(".box").innerHeight(true).toFixed(2); var neededSize = (containerHeight/100*40.32).toFixed(2); alert(containerHeight ); container.css("font-size", neededSize + "px"); } $(window).resize(foo); $(document).ready(foo); 

The resizing method is not reliable. The code in the resize handler should never rely on the number of calls to the handler. Depending on the implementation, resizing events can be sent continuously as they are resized (typical behavior in Internet Explorer and WebKit browsers such as Safari and Chrome), or only once at the end of the resize operation (typical behavior in some other browsers, such as Opera).

+1
source

I tried with this, it worked for me, and both give the same result for me. try container.css("font-size":neededSize + "px");

-1
source

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


All Articles