Resizing font based on html length - javascript

I know there are a lot of similar posts, but I have not thus far been able to solve this.
context:
User selects a home,
homes have unique titles,
depending on title, resize font to prevent overflow
JS Fiddle: https://jsfiddle.net/9uvpun5o/3/
$(function() {
var that = $('#title'),
planName = that.html().length
;
// depending on html length, update font-size
if(planName > 30) {
that.css('font-size', '10px');
} else if(planName > 20) {
that.css('font-size', '12px');
} else if(planName > 10) {
that.css('font-size', '15px');
}
});
Font is sized according to html length, but I need this to be reactive. I tried creating an .on("change") event, but failed to implement correctly. Help?
Right now I'm just updating the title from console,
$('#title').html("big long description thing");
But, this will be done by selecting from a modal menu in the future.

EDIT
Ok, now I got it. Your JS should be this then:
$(function() {
$('#title').on('DOMSubtreeModified', function() {
var title = $('#title'),
planName = title.html().length;
// depending on html length, update font-size
if(planName > 30) {
title.css('font-size', '10px');
} else if(planName > 20) {
title.css('font-size', '12px');
} else if(planName > 10) {
title.css('font-size', '15px');
}
});
$('li').on('click', function() {
$('#title').text( $(this).text() );
});
});
The DOMSubtreeModified should fire whenever the content of the element changes (as this modifies the DOM Subtree). The 'click' part is not necessary, but I've kept it for testing purposes.
According to Dottoro, Opera doesn't support this event and IE 9 and below may not support or be buggy.
For more options and informations, check these other StackOverflow question:
The question from where I got this solution
Suggestion with Mutation Events API
By what you said, an user will "select a unit":
use case:
User selects a unit,
units have unique titles,
depending on title, resize font to prevent overflow
So, you need to change the font-size as part of this action. I used your code to make an example:
HTML
<ul>
<li>On load, font size is set depending on length of title.</li>
<li>However, I want this to be reactive...</li>
<li>Change the length of Title and hit run</li>
<li>Try clicking these itens</li>
<li>You will see</li>
<ul>
<br/><br/>
<span id="title">TEST TEST</span><br/>
JS
$(function() {
$('li').on('click', function() {
var titleEl = $('#title').text( $(this).text() ),
planName = titleEl.text().length;
// depending on text length, update font-size
if (planName > 30) {
titleEl.css('font-size', '10px');
} else if (planName > 20) {
titleEl.css('font-size', '12px');
} else if(planName > 10) {
titleEl.css ('font-size', '15px');
}
});
});
Try to click in the list itens. You see? As a response to "changing the unit", the title and font-size changes.
If this answer doesn't help you, give more details.

I might do this with a combination of a bit of CSS to prevent the text from wrapping, then I would use some script to measure the length of the rendered text. If it's longer than whatever your predetermined maximum width is, use the script to apply a CSS transform.
#title {
white-space: nowrap;
display: inline-block; /* necessary for the scale to actually work */
transform-origin: 0% 100%; /* set transform origin to bottom left corner of the title element */
}
.maxwidth-container {
width: 400px;
}
Then in your script:
var scaleTitle = function() {
var $title = $("#title");
var maxWidth = $(".maxwidth-container").width();
$title.css("transform","scale(1,1)"); //reset to normal scale in order to measure natural width
if ($title.width() > maxWidth) {
var scaleAmt = maxWidth / $title.width();
$title.css("transform" , "scale(" + scaleAmt + "," + scaleAmt + ")");
}
};
In your case, I have wrapped your #title element in a container that dictates the maximum size, but you could use an explicit set amount.
Call this function every time the user selects a home.
Example here:
https://jsfiddle.net/9uvpun5o/5/

This will work.TRy this
var planName = $("#title").text().length;
if(planName > 30) {
$('#title').css("fontSize", "16px");
}else{ if(planName > 20) {
$("#title").css("fontSize", "12px");
}else if(planName > 8) {
$("#title").css("fontSize","24px")
}

Related

How to fill progress bar based on number of letters typed?

I am trying to make an input box that has a div on the bottom which will act sort of a progress bar to tell you when you have enough characters typed.
I can't get this animation to work, even though I thought it would be a lot easier when I decided to try this project.
Please let me know what is wrong with my code. Thanks!
<div id='cntnr'>
<div id='inptDiv'>
<input id='inpt1'>
<div id='prgInd'></div>
</div>
</div>
var main = function() {
var inptAmnt = document.getElementById('inpt1').value;
if(inptAmnt.length === 1) {
$('#prgInd').css('width', 25);
}
}
$(document).ready(main);
I also tried this code first but it didn't work either:
var main = function() {
var inptAmnt = document.getElementById('inpt1').value;
if(inptAmnt.length === 1) {
$('#prgInd').animate({
width:25
},200 )
}
}
$(document).ready(main);
JSFiddle: https://jsfiddle.net/qcsb53ha/
You can use jQuery to listen to the change, keyup and paste events of your text input.
Then, work out a percentage, based on your desired input length; and use this percentage to set the width of the progress bar.
If the "percentage" is above 100 - just reset it to 100 again. jQuery code is below:
var desiredLength = 4; // no jokes please...
// Listen to the change, keyup & paste events.
$('#text-box').on('change keyup paste', function() {
// Figure out the length of the input value
var textLength = $('#text-box').val().length;
// Calculate the percentage
var percent = (textLength / desiredLength) * 100;
// Limit the percentage to 100.
if (percent > 100) {
percent = 100;
}
// Animate the width of the bar based on the percentage.
$('.progress-bar').animate({
width: percent + '%'
}, 200)
});
See the working JSFiddle here : https://jsfiddle.net/jqbka5j8/1/
I've included normal code for setting the width, and the code for animating the width. You can comment/uncomment the necessary ones and test appropriately.
Hope this helps!
There's no need the use of javascript, you can use only pure CSS and Content Editable:
HTML
<div>
<span contenteditable="true">sdfsd</span>
</div>
CSS
span
{
border: solid 1px black;
}
div
{
max-width: 200px;
}
JsFiddle example

Change color Navigation Div when it passed from specific div

I want to change the color from white to black and/or black to white of my navbar-toggle.
But the problem is when it reach a sepecific div with a specific class like 'white' or 'black' the color changes when the scroll begins.
var stickyOffset = $(".navbar-toggle").offset();
var $contentDivs = $("section");
$(document).scroll(function() {
$contentDivs.each(function(k) {
var _thisOffset = $(this).offset();
var _actPosition = _thisOffset.top - $(window).scrollTop();
if (_actPosition < (stickyOffset.top + $('.navbar-toggle').height()/2) && _actPosition + $(this).height() - $('.navbar-toggle').height()/2 > 0) {
$(".bar1, .bar2, .bar3, .navbar-span").removeClass("white black").addClass($(this).hasClass("white") ? "white" : "black");
}
});
});
Now my jsfiddle but it changes very fast and I don't know what i'm doing wrong.
http://jsfiddle.net/xarlyblack/8mn4bucw/
Thank you in advance!
Best,
Carl
I dont know if I understand correctly your problem, but it seems to me that you have a logic error with your color label assignment, I think it should be like this:
...
if (_actPosition < (stickyOffset.top + $('.navbar-toggle').height()/2) &&
_actPosition + $(this).height() - $('.navbar-toggle').height()/2 > 0) {
$(".bar1, .bar2, .bar3, .navbar-span").removeClass("white black")
.addClass($(this).hasClass("white") ? "black" : "white");
}
...
And here is an updated jsfiddle in which I think it is properly working
As others have already pointed out, in your jsfiddle the two classes should be switched, but if i understand you correctly, on initial page load the classes also do not match if you, for example already scrolled down and make a page reload/refresh or you come from a anchor link.
To fix this i would suggest you also run the class-switch after document load like this:
var stickyOffset = $(".navbar-toggle").offset();
var $contentDivs = $("section");
$(document).scroll(function() {
checkcolor();
});
$(document).ready(function() {
checkcolor();
});
function checkcolor()
{
$contentDivs.each(function(k) {
var _thisOffset = $(this).offset();
var _actPosition = _thisOffset.top - $(window).scrollTop();
if (_actPosition < (30 + $('.navbar-toggle').height()/2) && _actPosition + $(this).height() - $('.navbar-toggle').height()/2 > 0) {
$(".bar1, .bar2, .bar3, .navbar-span").removeClass("white black").addClass($(this).hasClass("white") ? "black" : "white");
}
});
}
I added a function call on document ready, and removed your stickyOffset Variable, because on page reload/refresh you are positioned in the middle of the site, the offset is way of. Your stickyOffset needs to be a fixed value. I just added the default number of 30 in.
See a fiddle here:
http://jsfiddle.net/5gcemfz0/3/
Seems like the problem is in
$(".bar1, .bar2, .bar3, .navbar-span").removeClass("white black").addClass($(this).hasClass("white") ? "white" : "black");
that place. It says that 'if $(this) has class 'white' add 'white' else add 'black'. Should change places. Hope it helps!

How to append html element one time when specific screen resolution range occurs?

My html:
<div id="log">
</div>
My jQuery:
$(function() {
var win = $(window);
resizeHandler();
win.resize(resizeHandler);
function resizeHandler() {
if (win.width() <= 700) {
$("#log").append("<div>" + "success" + "</div>");
}
}
});
I want that when a specific screen resolution range occurs, the <div>success</div> element would be displayed one time in the "log" div element. For example: from 1 px to 700 px screen resolution the success must be displayed in the "log" div element one time, and when the screen resolution is out of the 1 px to 700 px range the <div>success</div> must be removed from the "log" div element. How should the code look like?
$(function() {
var win = $(window);
resizeHandler();
win.resize(resizeHandler);
function resizeHandler() {
if (win.width() >= 700) {
if ($('#log').children().length == 0)
$("#log").append("<div class='suc'>" + "success" + "</div>");
} else {
$('.suc').remove();
}
}
});
If you really want to append just one element. But, i would use media queries too, and hide/show desired element...
Based on information provided in the comments, you want a simple media query. No JS required. If that's what you really needed to do then #nevermind's answer was perfect.
Just change your code like this.
HTML:
<div id="log">
<div id="success">Success</div>
</div>
CSS:
#success {
display: none;
}
#media only screen and (max-width: 700px) {
#success {
display: block;
}
}
You could create a boolean variable and set it to true when appending
+ create an else statement in your resizeHandler to cope with the other screensizes.
But in a real world example i would have solved this issue by using CSS mediaqueries.

How to make a .fixed sticky item's "margin-top" relative to the size of the sticky item?

This is my first question. I am having trouble with a image I am trying to stick when it reaches the top of the page after scrolling.
Check out this jfiddle - it is not mine but comes close to representing my question
http://jsfiddle.net/vBy5w/
(I am aware that I can input a set "margin-top" to make this work but when the browser size changes then the image size will respond and will throw off the set margin.)
So far I have achieved this by using the code below to effect the Div Id = Picture1 in my html
<div id="picture1"><img src="img/empty-restaurant.png" alt="Why do your customers not come back?" style="max-width:100%;height:auto;"> </div>
When this picture "sticks" the test below the image will jump up, I fixed this by including the last line of the .js but by stating a fixed "margin-top" it means that there will be a jump if the margin size is not correct depending on browser size.
Is there a way to make this Margin variable or relative to the height of the "stick"-ed item? And if so how?
Thanks guys!
$(document).ready(function() {
var s = $("#picture1");
var pos = s.position();
$(window).scroll(function() {
var windowpos = $(window).scrollTop();
//$("#header_left").html("Distance from top:" + pos.top + "<br />Scroll position: " + windowpos);
if (windowpos >= pos.top) {
s.addClass("stick");
} else {
s.removeClass("stick");
}
This is the part that needs changing - the first "margin-top" needs to be relative to the size of the "stick"ed item
if (windowpos >= pos.top) { s.addClass("stick"); $("body").css("margin-top", 60); } else { s.removeClass("stick"); $("body").css("margin-top", 0); }
});
});
As comments,
$("body").css("margin-top", s.height());
Gives a dynamic margin-top css value to the <body> based on the height on the element ( #picture1 ) that is being fixed during window.scroll
As an addition, you mention that the height may change on screen resize ( rwd )
So this may be good to add also ( to keep it in check )
$(window).resize(function() {
var s = $("#picture1");
if(s.hasClass("stick") {
$("body").css("margin-top", s.height());
}
});

jQuery image resizing issue

I've found this line of code somewhere using firebug and I know you need to put something where I've put the 3... behind parseFloat, but I have no idea what.
It works when I fill in a random number but the width is never the correct one and want to use it on several pages with photographs so it's always the correct size.
script type="text/javascript">
var badBrowser = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32");
$(document).ready(function(){
var scaledwidth = ((parseFloat(...)*($(window).height()/4000))+50).toFixed(0);
if (badBrowser) {
$('#container img').css('height',$(window).height()+'px');
}
$('#container').css('width',scaledwidth+'px');
imageresize();
});
jQuery(window).resize(function() {
var scaledwidth = ((parseFloat(...)*($(window).height()/4000))+50).toFixed(0);
if (badBrowser) {
$('#container img').css('height',$(window).height()+'px');
}
$('#container').css('width',scaledwidth+'px');
imageresize();
});
function imageresize() {
var height = $(window).height();
if ((height) > 1340){
var quality='1440';
} else if((height) > 980) {
var quality='1080';
} else if((height) > 680) {
var quality='720';
} else if((height) > 480) {
var quality='640';
} else {
var quality='320';
}
}
</script>
Thanks in advance!
It looks to me like the value you need to put there depends on the sum of the widths of all the images; so you can't just pick a value that works for all pages.
On the other hand, it also seems like a bad solution to the problem of keeping the images next to each other. Why set the width of the container? If you just ensure white-space doesn't wrap then all the images should sit next to each other without worrying about the container's width.
#container
{
white-space: nowrap; /* keep images on the same line */
font-size: 0; /* removes whitespace between images */
}
http://jsfiddle.net/f8y4Z/
From the javascript, we now only need the imageresize() (provided we use it to set different quality source images), and trigger it on ready and resize; no magic numbers required.
(For backwards compatibility with browsers that don't or poorly support white-space, you could use <nobr></nobr>)

Categories

Resources