I'm trying to make the font size be responsive and auto adjust the font size depends on width & height of the container(image).
But problem now is when I make the screen size smaller, It keep run the font size "1em" only. It start from // font size in the script, Thank you! :)
can I know where is the problem?
$(function() {
// document
'use strict';
var t1 = $('div.cp');
// Settings
t1.each(function() {
var _t1 = $(this);
// Different Data type
if (_t1.data('type') == "c1")
{
_t1.addClass('red').css(
{
"background-image" : "url('https://www.planwallpaper.com/static/images/violet-vector-leaves-circles-backgrounds-for-powerpoint_PdfkI4q.jpg')",
"background-size" : "100% 100%"
}
);
_t1.append(
'<div class="title">' + 'im red' + '</div>'
);
$(_t1.children()).wrapAll("<div class='ty-container'/>");
} else {
return false;
}
});
// alignment to middle
$('.cp').on('resize',function() {
$(".ty-container").css('margin-top', function() {
return($('.cp').height() - $(this).height()) / 2
});
}).resize();
// font size
textfit();
$(window).on('resize', textfit);
function textfit() {
var w1 = $('.cp').width()-10;
var w2 = $('.title').width();
var wRatio = Math.round(w1 / w2 * 10) / 10;
var h1 = $('.cp').height()-10;
var h2 = $('.title').height();
var hRatio = Math.round(h1 / h2 * 10) / 10;
var final = Math.min(wRatio, hRatio);
$('.cp').css('font-size', final + 'em');
}
});//end
.cp{width:340px;height:156px;display:table;text-align: center;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="cp" data-type="c1"></div>
Use font size vw that means viewport width. Must declare viewport width meta at header. and use font-size in css. example font-size: 50vw;
Related
I have a piece of code in my angular component:
IncreaseFontSize()
{
let FontSize:any = document.body.style.fontSize;
if(!FontSize)
{
FontSize = 1.4;
}
else
{
FontSize = parseFloat(FontSize);
}
document.body.style.fontSize = (FontSize+0.1) + 'rem';
}
DecreaseFontSize()
{
let FontSize:any = document.body.style.fontSize;
if(!FontSize)
{
FontSize = 1.4;
}
else
{
FontSize = parseFloat(FontSize);
}
document.body.style.fontSize = (FontSize-0.1) + 'rem';
}
These functions are called upon clicking two buttons, but it is not changing the font size of elements which have a font size already defined for them.
I need to increase/decrease the font size of all elements, i.e. if a label has font size 12px, a paragraph with font size of 11px, a div with font size 1.2rem the should increase their font size by 0.1 rem on click of the increase button.
How should I proceed with the approach?
Thanks in advance.
Try something like this. You can see the div with px does not grow, while other one does.
var fontSize = 16;
function IncreaseFontSize() {
fontSize = (fontSize + 1);
document.body.style.fontSize = fontSize + 'px';
}
function DecreaseFontSize() {
fontSize = (fontSize - 1);
document.body.style.fontSize = fontSize + 'px';
}
body,
.font-constant {
font-size: 16px;
}
.font-varies {
font-size: 1em;
}
<button onclick="IncreaseFontSize()">+</button>
<button onclick="DecreaseFontSize()">-</button>
<div class="font-varies">
Hello
</div>
<div class="font-constant">
how are you?
</div>
In my case, I also would like to get the value of the fontSize that comes from the CSS. This is particularly important when you dont initialise this value in the Javascript context nor within the inline CSS in the body tag. The tactic here is basically to save the offset and infer the original value of the css with the unit rem which is the relative font size based on the root element:
private fontSizeOffset = 0;
increaseFontSize() {
document.body.style.setProperty(
'font-size',
`calc(1rem + ${++this.fontSizeOffset}px)`
);
}
decreaseFontSize() {
document.body.style.setProperty(
'font-size',
`calc(1rem + ${--this.fontSizeOffset}px)`
);
}
my problem today is that I have 12 elements with size 60px x 60px and I'd like to increase the size with 0.2 everytime the screen size increase of 10px, with javascript. For example: screensize 600px and element size 60.2 x 60.2, screensize 610px and element size 60.4 x 60.4 and so on. It would give something like this to increase :
var circle_data={
container: document.querySelector(".container"),
classname: "astro-item",
nb_elem: 12,
elem_size: 60,
};
var screenSize = window.innerWidth;
circle_data.elem_size += 0.2;
The thing is that I don't know how to increase everytime the screen size increase by 10px
Thanks for your help !!
So with your answers here's the code I tried but it doesn't work, maybe because I already have a function that set elements size up, here's the full script:
function circle_container(objdata) {
var circle_dim=objdata.container.getBoundingClientRect();
var rayon=Math.round(circle_dim.width/2 - objdata.elem_size/2);
var center_x=rayon;
var center_y=rayon;
if (objdata.rayon) rayon*=objdata.rayon/100;
for(var i=0;i<objdata.nb_elem;i++) {
var new_elem=objdata.container.querySelector("."+objdata.classname+i);
if (!new_elem) {
var new_elem=document.createElement("button");
new_elem.className="astro-item"+" "+objdata.classname+i;
var new_img=document.createElement("img");
new_img.src = astroList[i].icon;
}
new_elem.style.position="absolute";
new_elem.style.width=objdata.elem_size+"px";
new_elem.style.height=objdata.elem_size+"px";
new_elem.style.top=Math.round( (center_y - rayon * Math.cos(i*(2*Math.PI)/objdata.nb_elem)))+"px";
new_elem.style.left=Math.round( (center_x + rayon * Math.sin(i*(2*Math.PI)/objdata.nb_elem)))+"px";
objdata.container.appendChild(new_elem);
new_elem.appendChild(new_img);
}
}
var circle_data={
container: document.querySelector(".container"),
classname: "astro-item",
nb_elem: 12,
elem_size: 60,
};
function onResize(e) {
var screenSize = e.target.outerWidth;
var width = (screenSize - (screenSize % 100) + (((screenSize + 10) % 100)/10 *2))/10;
var items = document.querySelectorAll('.astro-item');
for(var i = 0; i < items.length; i++) {
items[i].innerHTML = 'width: ' + screenSize + ' size: ' + width ;
}
}
circle_container(circle_data);
addEvent(window,"resize",function() {
circle_container(circle_data);
onresize();
});
The purpose of this function is to create 12 buttons aligned in circle (just like a wheel) and fully responsive, that's why I need them to get bigger when the screen gets larger. Thank you so much !
With pure javascript bind an event onresize and set size based on window width. The size increase 0.2 everytime the screen size increase of 10px:
window.addEventListener("resize", onresize);
var onresize = function(e) {
var width = e.target.outerWidth;
circle_data.elem_size = (width - (width % 100) + (((width + 10) %
100)/10 *2))/10;
}
Working example:
(open in full screen)
*Edited for max min limitations
var min = 500; //min width in pixel
var max= 700; //max width in pixel
window.addEventListener("resize", onresize);
var onresize = function(e) {
var width = e.target.outerWidth;
var s = (width - (width % 100) + (((width + 10) % 100)/10 *2))/10
if(width <=max && width >=min){
//change size here
document.getElementById('s').innerHTML = 'width: ' + width + ' size: ' + s ;
}
}
<span id='s'> </span>
What I am trying to do
I want to display multiple images in the same div of fixed size like the image. There will be multiple divs in the same page. The total size of the divs should not exceed the size of the screen.
function setupView(div, items, height, percentage) {
//get the height for the div
//var max_height = getPossibleHeight(div, items);
if(percentage){
$(div).css("height" , $(window).height() / 100 * height);
} else
$(div).css("height" , height+"px");
$(div).css("line-height",0);
//get the computed height and width
const div_height = $(div).height();
const div_width = $(div).width();
//Calculate the side of each image
const im_side = parseInt(getItemSize(div_width, div_height, items));
var count;
var dv = $(div);
for(count=0; count <= items; count++){
dv.append("<img style='height: "+ im_side +"px;"+" width: "+ im_side+"px" +"' src='../images/done.png'/>");
}
}
function getItemSize(x, y, n) {
var px = Math.ceil(Math.sqrt(n*x/y));
var sx,sy;
if(Math.floor((px*y)/x)*px < n){
sx = y/Math.ceil(px*y/x);
} else{
sx = x/px;
}
var py = Math.ceil(Math.sqrt((n*y)/x));
if(Math.floor((py*x)/y)*py<n){
sy = x/Math.ceil((x*py)/y);
}
else {
sy = y/py;
}
// alert("X="+sx + " Y="+sy);
// if(x>y)
return (sx>sy) ? sx : sy;
}
$(function() {
setupView(".panel-4",25000,"60",true);
// setupView(".panel-5",9000);
alert("Load complete!");
});
This is what is happening right now:
Current Situation
I have used the code provided on
C Code
I want to resize the images in such a way that they fill the div completely without leaving any space.
I'm wrapping up a site that involves a few elements (image / text / diagonal line) that have to scale proportionately on different screens.
Because there's text that has to be resized, I'm using jQuery to calculate the measurements for all of the elements based on a ratio. This was the best solution I could think of at the time, and with a deadline approaching, I think I'm stuck with it. It's a single-page site that scrolls by the page (e.g., full pages in the viewport).
Here's a link to the demo site
The idea behind the code:
We check the height of the viewport to set the container size
Set the wrapper element height, based on the container size and necessary
margins
Set the width based on a ratio
Use these values to calculate font size, image size, and offsets
As the screen is re-sized, the element shrinks proportionately to fill the available space.
It looks kind of like this:
There are two panels like this. I re-use the same code (with different variable names, and a few sizing differences) for the second panel.
Here's my Javascript/jQuery for the first:
// Set panel height on page load & resize
$(window).on("resize", function () {
var $panelHeight = $(window).height();
var $headerHeight = $('.banner').height();
// General height for panels
$('.bg-panel').css('height', $panelHeight );
$('.bg-panel').css('padding-top', $headerHeight);
}).resize();
// We want to scale content proportionately
// First let's get some breakpoints
var $breakPoint = 768;
var $breakPointSM = 480;
// Panel 1
$(window).on("resize", function () {
// Check height of current panel
// If on single-column view, we want to measure the space between the text column and bottom of screen
// Otherwise, height of entire panel
var $windowHeight = $('.panel-test').height();
// But we need to subtract the header height, so our math is correct
var $headerHeight = $('.banner').height();
var $windowHeight = $windowHeight - $headerHeight;
// Now we have the correct height to work with
// We're at 768px or below, subtract the text element from the overall height
if ( $(document).width() <= $breakPoint) {
var $heightofDiv = $('.panel-1-text').height();
var $mobileHeight = $windowHeight - $heightofDiv;
var $windowHeight = $mobileHeight;
}
// Save the window height for calculating our margins!
var $windowHeightforMargins = $windowHeight;
// Top and bottom margins
var $marginTop = $windowHeight * (102/792); // ratio from PSD
var $marginBottom = $windowHeight * (84/792); // ratio from PSD
var $marginTotal = $marginTop + $marginBottom;
// Responsive solution
// As browser shrinks, reduce the height of panel so it produces a smaller container
if ( $(document).width() > 1200 && $(document).width() <= 1440) {
var $windowHeight = $windowHeight * 0.9;
var $marginTop = $marginTop * 2;
}
else if ( $(document).width() > 990 && $(document).width() <= 1200) {
var $windowHeight = $windowHeight * 0.8;
var $marginTop = $marginTop * 3;
}
else if ( $(document).width() > $breakPoint && $(document).width() <= 990) {
var $windowHeight = $windowHeight * 0.7;
var $marginTop = $marginTop * 3.5;
}
else if ( $(document).width() < $breakPoint) { // Ratio here goes up again because we're accounting for new height with $mobileHeight
var $windowHeight = $windowHeight * 0.8;
}
// This ratio determines the width of the container
var $ratio = 697 / 607; // from PSD
// Set container height, depending on height of panel
if ( $(document).width() <= $breakPointSM) {
var $taglinesHeight = ($windowHeight * 1.5); // Scale up for phones
}
else if ( $(document).width() > $breakPointSM && $(document).width() <= $breakPoint ){
var $taglinesHeight = ($windowHeight * 1); // Scale down for tablet
}
else {
var $taglinesHeight = $windowHeight - $marginTotal;
}
// Set container width as ratio of height
if ( $(document).width() <= $breakPoint) {
var $taglinesWidth = $taglinesHeight * $ratio
} else {
var $taglinesWidth = $taglinesHeight * $ratio
}
$('.panel-test .bg-taglines').css("width", $taglinesWidth);
$('.panel-test .bg-taglines').css("height", $taglinesHeight);
// Add top margin if above breakpoint
if ( $(document).width() > $breakPoint) { // No margin unless above 768px
$('.panel-test .bg-taglines').css("margin-top", $marginTop);
}
else {
$('.panel-test .panel-1-tagline').css("bottom", $marginTop);
}
// Set font size
var $fontSize = $taglinesWidth * 0.12;
$('.bg-panel h4').css("font-size", $fontSize);
// Set pink line origin (relative to bottom-left of frame)
var $pinkX = $taglinesWidth * (286 / 705);
var $pinkY = $taglinesHeight * (192 / 607);
$('.panel-test .animation-wrapper').css("left", $pinkX);
$('.panel-test .animation-wrapper').css("bottom", $pinkY);
// Set image size
var $imageWidth = $taglinesWidth * 0.556;
$('.panel-test .scaleable-image').css("width", $imageWidth);
// Set h3 margin from top
if ( $(document).width() >= $breakPoint) {
var $marginH3 = $windowHeight * (217/792); // ratio from PSD
$('.panel-test h3').css("margin-top", $marginH3);
} else {
// CSS
}
// Set line offset from top
var $lineOffset = $taglinesHeight * 0.7;
$('.panel-test .line-wrapper').css("top", $lineOffset);
// Set line length
var $lineLong = $taglinesWidth * 1;
$('.panel-test .pink-line').css("width", $lineLong);
}).resize();
It works: MOST of the time.
If I drag my window to resize, some of the elements get resized. Others don't.
A page refresh generally solves it, but right now, elements (mostly the images!) just aren't scaling properly and in sync with other elements.
I'm very new to jQuery and this is my first big undertaking. New to using resize as well. Hoping I just made a goof that's easy to fix.
Thanks!
LIVE SITE LINK
Other plugins in use: jQuery Scrollify (for full page scrolling) and ScrollReveal.
Guess I can answer my own question.
The issue seemed to be that the values were getting mixed up when scrolling from one full-screen panel to another.
Changing this:
$(window).on("resize", function () {
To this:
$(window).on("resize load scroll", function (e) {
... solved the issue. I'm not sure if it's the right way to do it, but the resizes are all working fine now.
I wrote a basic program that moves a button inside a DIV element. The button is not staying within the area I had intended. On the HTML side I have code that defines the DIV with an id = "page". Here is the js code. Why is the button not staying within the DIV element?
var buttonState = document.getElementById("clickMe");
var maxWidth = document.getElementById("page");
var maxHeight = document.getElementById("page");
var pageWidth = maxWidth.clientWidth;
var pageHeight = maxHeight.clientHeight;
var screenWidth = 0;
var screenHeight = 0;
function moveButton() {
"use strict";
// Find max width and height of screen and set variables to random number within parameters
screenWidth = Math.floor(Math.random() * (pageWidth)) + 1;
screenHeight = Math.floor(Math.random() * (pageHeight)) + 1;
console.log(screenWidth);
console.log(screenHeight);
// Button position
buttonState.style.left = (screenWidth) + "px";
buttonState.style.top = (screenHeight) + "px";
// Button size
buttonState.style.width = buttonSize + "em";
buttonState.style.height = buttonSize + "em";
In your equations for screenWidth and screenHeight you need to take into account the size of the button.
The div is positioned based on the top left pixel so if you end up with Math.random() returning 1 or something very close to it, the button will fall out of the page unless you subtract the button sizes from the maxes.
var buttonWidthPx = buttonState.offsetWidth;
var buttonHeightPx = buttonState.offsetHeight;
screenWidth = Math.floor(Math.random() * (pageWidth - buttonWidthPx)) + 1;
screenHeight = Math.floor(Math.random() * (pageHeight - buttonHeightPx)) + 1;
Also make sure to set the positioning of the button to relative so it positions inside the div and not absolute to the document.
First thought, it is probably more of a css layout issue than javascript or html.
The first clue to this is
buttonState.style.left
buttonState.syyle.top
If you check the buttonState in Chrome DevTools you might find the layout to be: absolute and that would be one good reason why it does not layout as intended. Another would be if layout is set to static.
Here is a link that gives good depth of information on css layout settings: http://alistapart.com/article/css-positioning-101
The first thing I would try would be to open DevTools and deselect (remove) all the styles that buttonState has until you find the layout that is causing the problem.
I don't know the exact problem that you are facing because you didn't provide any HTML/CSS, but check out this fiddle for a working example.
<div id="page">
<button id="clickMe">Click Me</button>
</div>
<button id="move">Move Button</button>
#page {
width:300px;
height: 300px;
background-color: whitesmoke;
}
#clickMe {
position: relative;
top: 0;
left: 0;
}
var page = document.getElementById("page");
var pageWidth = page.clientWidth;
var pageHeight = page.clientHeight;
var button = document.getElementById("clickMe");
var buttonWidth = button.clientWidth;
var buttonHeight = button.clientHeight;
function moveButton() {
var x = Math.floor(Math.random() * (pageWidth - buttonWidth));
var y = Math.floor(Math.random() * (pageHeight - buttonHeight));
button.style.left = x + "px";
button.style.top = y + "px";
}
document.getElementById("move").onclick = moveButton;