resizing text of whole document using jquery - javascript

i want to resize the font of all elements of a page
like user can click increaseFont or decreaseFont this will decrease the fonts of all elems
iam doing doing as writen below
please suggest some better way
$.fn.ChangeFont=function(ratio)
{
return this.each(function(){
var _elm=$(this);
var currFontSize = _elm.css('fontSize');
var finalNum = parseFloat(currFontSize, 10);
var stringEnding = currFontSize.slice(-2);
finalNum *= ratio;
finalNum=finalNum + stringEnding;
_elm.css('fontSize',finalNum);
});
}
$(document).find('*').andSelf().ChangeFont(1.2);//a value bigger than 1 for increase
$(document).find('*').andSelf().ChangeFont(.8);//a value smaller than 1 for decrease

Could you not just set the font-size property on the BODY element to be 125% or 150%?
$("body").css("font-size", "150%");

This is dependent on how the rest of your CSS is structured and what units you are using to assign font-sizes in the rest of the page. If you are using em or % then it is enough to do just like Chase Seibert says:
$("body").css("font-size", "150%");
So simply use the correct units in your CSS and then manipulate the main body text-size. Otherwise you can also choose an element like a div which acts as the root element of all textual content on the page you are creating.
As a comment by #praveen also says is that this will not necessarily affect you non-textual content.

Related

JavaScript or Jquery, create style rule

So, it's easy enough to do something like
$('.someClass').css(....);
That adds an inline style directly into the HTML. But what if I wanted to create an actual rule?
.someClass {
....
}
And then be able to edit that new rule on something like window.resize().
What I am trying to do is write a script that generates a font size dynamically, and then applies it to all elements of a certain class equally (it resizes the text so that it stays on one line). Every time the window resizes, the script sets the font to 3, and then loops through, incrementing the font size by 1, until it is as big as it can be without breaking to another line (exceeds a given height). Here is the full script for reference.
$.fn.fitText = function (height) {
return this.each(function () {
console.log(this);
$(this).css('font-size', '3px');
var newSize;
while ($(this).height() < height) {
newSize = parseInt(jq11(this).css('font-size'), 10) + 1;
$(this).css('font-size', newSize);
}
newSize = parseInt($(this).css('font-size'), 10) - 1;
$(this).css('font-size', newSize);
});
};
That works, in that I can call
$('.sectionTitle').fitText(25);
And it will run on all instances of that text, increasing their sizes until they are as big as they can be and still be less than 25px high (one line). But it does it to each element individually, leading to varying text sizes and just looks goofy. I'd like it so that it calculates the maximum font size that it can set so that none of the elements is more than one line, and then applies that style to all elements.

How do I create a div the size of the page?

Note that I'm not asking how to make a div the size of the "window" or "viewport" for which there are plenty of existing questions.
I have a web page of some height and width, and I'd like to add an empty, top-level div (i.e., not one containing the rest of the page) with a size exactly equal to the page's height and width. In practice, I also want it to be at least the size of the viewport.
I know I can do a one-time calculation of the height and width in JavaScript:
var height = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);
var width = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);
But this value can change based on images loading, or AJAX, or whatever other dynamic stuff is going on in the page. I'd like some way of locking the size of the div at the full page size so it resizes dynamically and on-demand.
I have tried something like the following:
function resetFakeBg() {
// Need to reset the fake background to notice if the page shrank.
fakeBg.style.height = 0;
fakeBg.style.width = 0;
// Get the full page size.
var pageHeight = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);
var pageWidth = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);
// Reset the fake background to the full page size.
fakeBg.style.height = pageHeight + 'px';
fakeBg.style.width = pageWidth + 'px';
}
// Create the fake background element.
fakeBg = setFakeBgStyle(document.createElement('div'));
document.body.appendChild(fakeBg);
// Keep resizing the fake background every second.
size_checker_interval = setInterval(resetFakeBg, 1000);
Limitations
This is for a Chrome extension, and I'd like to limit my modification of the page to adding this single div. This means that adding CSS to modify the height and width of the html and/or body tags is undesirable because it might have side-effects on the way the rest of the page is rendered.
In addition, I do not want to wrap the existing page in the div because that has the potential to break some websites. Imagine, for example, a site styled with the CSS selector body > div. I'd like my extension to break as few websites as possible.
WHY OH WHY WOULD I NEED TO DO THIS?
Because some people like to hold their answers hostage until they're satisfied that I have a Really Good Reason™ for wanting to do this:
This is for an accessibility-focused Chrome extension that applies a CSS filter across an entire page. Recent versions of Chrome (>= 45) do not apply CSS filters to backgrounds specified on the <html> or <body> tag. As a result, I have chosen to work around this limitation by copying the page's background onto a div with a very negative z-index value, so that it can be affected by the page-wide CSS filter. For this strategy to work, the div needs to exactly imitate the way the page background would appear to a user—by being the exact size of the document (and no larger) and at least filling the viewport.
setInterval() is your best friend in cases like this where you want the .height() and .width() of an element to be asynchronously specified all the time to something that can be dynamicly altered by user input and DOM tree changes. It is what I dub as a "page sniffer", and arguably, works better than $(document).ready if you are working in multiple languages (PHP, XML, JavaScript).
Working Example
You should get away with setting the width and height in the window resize function, you might wanna add it in a load function as well, when all data/images are loaded.
just add width=100%
e.g;-
Hello World
I think you must do it like this:
...
<body>
<script>
function height()
{var height = Math.max(document.body.scrollHeight,
document.documentElement.clientHeight);}
function width()
{var width = Math.max(document.body.scrollWidth,
document.documentElement.clientWidth);}
</script>
<div height="height()" width="width()">
</div>
</body>
...

Setting up max-height and not overflow

Some background: I have a div in which elements of different height will be added to and I'm in need of achieving the following:
The div has a max-height property, when the different elements that are added to the Div overlap such height, I can't have the div "overflowing (putting a scrollbar on it)". Instead, I need to detect when this happens, so I can create ANOTHER div in which I could put the rest of the elements. Attached is an image that I hope illustrates what I'm trying to do.
Use jQuery:
var maxHeight = $(".someElement").css("max-height");
var height = 0;
$(".elements").each(function(){
height += $(this).height();
if(height >= maxHeight){
//create new div here and put the rest of the elements there
height = 0; //so you can continue with the loop and creating more divs.
}
});
I have a pseudo function below that I think could get you started on the right track. You will have to fill in the appropriate information for it.
$(elements).each(function() {
var currentDiv = $(currentDiv);
if($(currentDiv ).height() > MAX_HEIGHT)
{
$(currentDiv).insertAfter(newDiv);
currentDiv = $(newDiv);
}
$(currentDiv).append(element);
});
You'll have to keep track of the current div you are adding info to. Just add info like normal but when it overflows you should insertAfter it a new div and change the current div variable to be that one and then continue appending again.
To test if a div is currently overflowing, compare it's scrollHeight to its height.
With jQuery
if ($(obj)[0].scrollHeight > $(obj).height()) {
// do stuff
}
In this case though, you'll probably want to test against the css max-height before adding content. To do this (again in jQuery) load the content you plan to add into a variable so you can check its height before adding it to the document.
var content = // your content here
if ($(container).height() + content.height() > parseInt($(container).css("max-height"), 10)) {
// this means it would overflow, so do stuff
} else {
// no overflow here
$(container).append(content);
}
Here's a quick fiddle. http://jsfiddle.net/k0g47xdr/2/
edit:
the parseInt call around .css("max-height") is to convert from the text format it comes in to a regular number. As written it assumes the value is in px, not em or percent.

Get Default Height Of Element On Webpage after css height has been applied)

How do I go about getting what the height of an element on a page would be if it ignored the 'height' css property applied to it?
The site I'm working on is http://www.wncba.co.uk/results and the actual script I've got so far is:
jQuery(document).ready(function($) {
document.origContentHeight = $("#auto-resize").outerHeight(true);
refreshContentSize(); //run initially
$(window).resize(function() { //run whenever window size changes
refreshContentSize();
});
});
function refreshContentSize()
{
var startPos = $("#auto-resize").position();
var topHeight = startPos.top;
var footerHeight = $("#footer").outerHeight(true);
var viewportHeight = $(window).height();
var spaceForContent = viewportHeight - footerHeight - topHeight;
if (spaceForContent <= document.origContentHeight)
{
var newHeight = document.origContentHeight;
}
else
{
var newHeight = spaceForContent;
}
$("#auto-resize").css('height', newHeight);
return;
}
[ http://www.wncba.co.uk/results/javascript/fill-page.js ]
What I'm trying to do is get the main page content to stretch to fill the window so that the green lines always flow all the way down the page and the 'Valid HTML5' and 'Designed By' messages are never above the bottom of the window. I don't want the footer to stick to the bottom. I just want it to stay there instead of moving up the page if there's not enough content to fill above to fill it. It also must adapt itself accordingly if the browser window size changes.
The script I've got so far works but there's a small issue that I want to fix with it. At the moment if the content on the page changes dynamically (resulting in the page becoming longer or shorter) the script won't detect this. The variable document.origContentHeight will remain set as the old height.
Is there a way of detecting the height of an element (e.g. #auto-resize in the example) and whether or not it has changed ignoring the height that has been set for it in css? I would then use this to update the variable document.origContentHeight and re-run the script.
Thanks.
I don't think there is a way to detect when an element size changed except using a plugin,
$(element).resize(function() //only works when element = window
but why don't you call refreshContentSize function on page changes dynamically?
Look at this jsFiddle DEMO, you will understand what I mean.
Or you can use Jquery-resize-plugin.
I've got it working. I had to rethink it a bit. The solution is on the live site.
The one think I'd like to change if possible is the
setInterval('refreshContentSize()', 500); // in case content size changes
Is there a way of detecting that the table row has changed size without chacking every 500ms. I tried (#content).resize(function() but couldn't to get it to work.

Truncating html text appropriately into a fixed size area

In a generated html page, we have a fixed size area (lets say 200 x 300) in which we need to fit in as much text as possible (like a regular paragraph of text), and if it doesn't fit, remove an appropriate number of characters and append "..." to the end.
The text is NOT in a fixed sized font, and although we are using one specific font for this text, a "generic" solution would obviously be preferred.
This looked interesting, but I'm thinking it would be very slow with this function being called for several items on a page - http://bytes.com/topic/javascript/answers/93847-neatly-truncating-text-fit-physical-dimension
The solution can use an intermix of html, css, js, and php as needed.
Suggestions on approaches are more than welcome!
I'd say that the solution you found is the best. It is, for instance, used for this jQuery plugin which autoresizes textareas as you enter text into it. I took the concept and rewrote it with jQuery for this simple test here: http://jsfiddle.net/ZDr5K/
var para = $('#para');
var height = 200;
while(para.height() >= height){
var text = para.text();
para.text(text.substring(0, text.length - 4) + '...');
}
Possible improvements would include right trimming and removing the period if the last character is a full stop. Removing word by word would also be more readable/slightly faster.
As for the function running multiple times, that would be unavoidable. The only thing you can really do with CSS here is to use :after to append the ellipses, but even that should be avoided for cross-compatibility problems.
Set the element dimensions via CSS and its overflow to "hidden".
Then, find out with this function, if the element's content is overflowing (via):
// Determines if the passed element is overflowing its bounds,
// either vertically or horizontally.
// Will temporarily modify the "overflow" style to detect this
// if necessary.
function checkOverflow(el)
{
var curOverflow = el.style.overflow;
if ( !curOverflow || curOverflow === "visible" )
el.style.overflow = "hidden";
var isOverflowing = el.clientWidth < el.scrollWidth
|| el.clientHeight < el.scrollHeight;
el.style.overflow = curOverflow;
return isOverflowing;
}
Now, in a loop remove text and check until it is not overflowing anymore. Append an ellipsis character (String.fromCharCode(8230)) to the end, but only if it was overflowing.
To avoid any flickering effects during that operation, you can try working on a hidden copy of the element, but I'm not sure if the browsers do the necessary layout calculations on an element that's not visible. (Can anyone clarify that?)

Categories

Resources