I need to fit text in div box with exact width.
Is there a way (for example with javascript) to make the text look the same size in all major browsers?
For example strip some letters if text does not fit 'div' box.
Just add the following properties to the CSS rule for your div:
overflow:hidden; text-overflow:ellipsis; white-space:nowrap;
You can see this in action here (JSFiddle).
First of, set your font face and size with css. Then you will almost always have the same width.
Then you can add overflow: hidden; to your div so it won't show anything that goes past the end.
Depending on how you're doing this, you could use padding and margins without setting a width, that way it will always fit in the div. Although this may not be what you want.
You can truncate your text with CSS or with JavaScript. Here's an example of a simple JQuery truncation plugin I wrote which allows for a "show more" link if the text is truncated:
$.fn.trunc = function(_break_at) {
var _article = jQuery(this).text();
var _leader = [];
var _trailer = [];
var _substr = _article.split(' ');
$(this).wrapInner('<div class="long"></div>');
$.each(_substr, function(i, data) {
if (i < _break_at) {
_leader.push(data);
}
});
if (_substr.length > _break_at) {
$('<div/>').addClass('short').html(_leader.join(' ')).prependTo(this);
$('<span/>').appendTo('.long').addClass('toggle').html(' << Show less');
$('<span/>').appendTo('.short').addClass('toggle').html('... Show more >>');
}
$('.toggle').click(function() {
$('.short, .long').toggle('show');
});
};
$(function() {
// This is how you use it
$('#article_body').trunc(2);
});
http://jsfiddle.net/AlienWebguy/7ZamJ
Related
I have a responsive website, with some jQuery code, of which some is the following:
<script>
$(document).ready(function(){
$("#D1000C36LPB3").click(function(){$("#D1000C36LPB3_details").show();});
$("#D1200C36LPB3").click(function(){$("#D1200C36LPB3_details").show();});
$("#D1-3CA36LPB3").click(function(){$("#D1-3CA36LPB3_details").show();});
$("#D1-0CA36LPB3").click(function(){$("#D1-0CA36LPB3_details").show();});
$("#D700S36LPB3").click(function(){$("#D700S36LPB3_details").show();});
$("#D700S24LMB3").click(function(){$("#D700S24LMB3_details").show();});
});
</script>
All of the div elements above (#D1000C36LPB3_details, #D1200C36LPB3_details, #D1-3CA36LPB3_details...) have a CSS display property value of none, so by default they aren't visible until you click on one of the div elements above (#D1000C36LPB3, #D1200C36LPB3, #D1-3CA36LPB3...) and then the corresponding div is displayed.
However, when the jQuery script runs, it sets the corresponding div display value to block. When the viewport's/window's width is smaller than say 400 px, I want the script to display them with position: fixed;.
My suggestion
I've figured out I can display them with fixed position using:
$("#corresponding_ID").css("display", "fixed");
But I still have to not let jQuery run the first script (the one using .show()).
Don't set css styles directly this way. As already commented, use e.g. a .visible class and let css media queries decide. Example:
#media screen and (max-width: 399px) {
.visible {
display: fixed;
}
}
#media screen and (min-width: 400px) {
.visible {
display: block;
}
}
Then, in your click handler, go as follows:
$("#D1000C36LPB3").click(function(){$("#D1000C36LPB3_details").addClass('visible');});
Also, if your details containers all follow that naming scheme with affixing _details to the id, it'd be easier to put all ids in an array and iterate over that:
$(document).ready(function(){
var ids = [ "#D1000C36LPB3", "#D1200C36LPB3", "#D1-3CA36LPB3", "#D1-0CA36LPB3", "#D700S36LPB3", "#D700S24LMB3"];
for (var i = 0; i < ids.length; i++) {
$(ids[i]).on('click', function () { $(ids[i]+'_details').addClass('visible'); }
}
};
Easy way to check for browser width with Jquery:
var width = $(window).width();
if (width >= 1024) {
-- Code to execute here --
}else{
-- Other code to execute here --
}
Then you can adjust the width you are looking and update the >= based on what you want to do.
Let me know if this doesn't make sense.
I am making a price estimator.
How would correctly write a jQuery function that checks a variable and depending on that amount hides/shows a certain div element accordingly.
So if I had:
a HTML div with the ID 'Answer'
<div id="answer">Hide Me</div>
$("#answer")...
a variable (this variable would change)
var x = 30
Now I know the css to hide the div would be:
#answer{
visibilty:hidden;
}
What would be the correct way to hide the function checking these certain parameters? for example if x > 20 then hide etc
Now I know there will be many ways to do this and they may not require jQuery, please inform me if this is the case. Perhaps it just needs JS. I know there will be many ways to do it not just one so if you have a different way please comment as I am keen to learn.
Any help would be greatly appreciated.
Cheers
F
Note that you can also remove or add a class:
$('#answer').removeClass('hide');
$('#answer').addClass('hide');
But what you want to do is $('#answer').hide(); or $('#answer').show();
Execute this function providing the variable v:
var checkVar = function(v) {
var target = $('#answer');
if (parseInt(v) > 20) {
target.hide();
} else {
target.show();
}
}
For example, if the variable comes form a selection:
$('#selectId').on('change', function() {
checkVar($(this).val());
});
Remove the CSS. You can do it in jQuery
if(x>20){
$('#answer').hide();
}
You can use this one
$("#answer").hide();
#kapantzak's answer looks good. But keep your logic and style separated and if your not going to use the variable for the actual element twice, I wouldn't make it. So go:
var checkVar = function(var) {
var element = $('#answer');
if (parseInt(var) > 20) {
element.addClass('hidden');
}else{
element.removeClass('hidden');
}
}
And in your CSS go:
#answer.hidden{
display: none;
}
Also, depending on your preference, display: none; doesn't display anything of the object whereas visibility: hidden hides the object but the space the object was occupying will remain occupied.
HTML
<input id="changingValue">
...
<div id="answer">Hide Me</div>
CSS (not mandatory if you check values on loading)
#answer{ display:none;}
JS
var limit = 20;
$(function(){
$("#changingValue").change(function(){
if(parseInt($("#changingValue").val())<limit) { $("#answer").show(); }
else { $("#answer").hide(); }
});
});
https://auth.me.com/authenticate
On this website when you type in your email address , the font-size will automatically be reduced if the email address fills the box size.
How can we do the same using Javascript?
which are the events that are being fired / captured ?
$("input").keypress(function(){
if(this.value.length>43)//or some other value
{//do stuff here
}
});
Keydown is what you are looking for
I have made a library, named resize.js, which allow to write:
<input type="text" resize="true" />
This is the library:
var precision=18;
window.onload=function()
{
for(var i=0,t=document.getElementsByTagName("input"),l=t.length;i<l;i++)if(t[i].getAttribute("resize")==="true")
{
var div=document.createElement("div");
div.setAttribute("style","font-size"+parseInt(t[i].s("font-size"))+";font-family:"+t[i].s("font-family")+";position:absolute;top:-10000px;left:-10000px;");
document.body.appendChild(div);
(function(i,div,min,max,dif,l,r,w,h,pre){setInterval(function(){modify(t[i],div,min,max,dif,l,r,w,h,pre);},100);})
(
i,
div,
t[i].getAttribute("min")||parseInt(t[i].s("font-size"))-3,
t[i].getAttribute("max")||parseInt(t[i].s("font-size")),
parseInt(t[i].s("padding-left"))+parseInt(t[i].s("padding-right"))+parseInt(t[i].s("border-left-width"))+parseInt(t[i].s("border-right-width"))+precision,
parseInt(t[i].s("padding-left")),
parseInt(t[i].s("padding-right")),
t[i].offsetWidth,
t[i].offsetHeight,
precision
);
}
}
Object.prototype.s=function(p)
{
return this.currentStyle?this.currentStyle[p]:document.defaultView.getComputedStyle(this,null).getPropertyValue(p);
}
function modify(el,c,min,max,dif,l,r,w,h,pre)
{
el.style.width=w+"px";
el.style.height=h+"px";
c.innerHTML=el.value.replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/ /g," ");
var test=c.offsetWidth;
while(test>=el.offsetWidth-dif&&parseInt(el.s("font-size"))>min)
{
el.style.fontSize=parseInt(el.s("font-size"))-1+"px";
c.style.fontSize=el.style.fontSize;
test=c.offsetWidth;
}
while(test<el.offsetWidth-dif&&parseInt(el.s("font-size"))<max)
{
el.style.fontSize=parseInt(el.s("font-size"))+1+"px";
c.style.fontSize=el.style.fontSize;
test=c.offsetWidth;
}
if(parseInt(el.s("font-size"))===min&&c.offsetWidth>el.offsetWidth-dif)
{
el.style.paddingLeft="0px";
el.style.paddingRight="0px";
}
else
{
el.style.paddingLeft=l+"px";
el.style.paddingRight=r+"px";
}
}
A fiddle: http://jsfiddle.net/mageek/GEp2y/1
Some advices:
If the attribute "resize" equals anything other than true, or is not set, the text-box will behave as a normal text-box.
You can set the maximum font-size and the minimum font-size allowed by setting the "max" and the "min" attributes. By default, the maximum is the current font-size and the minimum is 3 sizes smaller than the maximum.
I added something, like https://auth.me.com/authenticate, which removes the padding to gain space when the minimum font-size is reached.
There is the variable 'precision' (at the beginning of resize.js) that depends on the text-box, I set it to 18 for default text-box but if you modify the style of the text-box, you will maybe have to modify the variable to a better value (by testing).
I don't ensure the host of resize.js on the website like in the fiddle, you should copy the source code in a new file and save it.
I've made the code for you, I took for example what I did on my own website for the contact form: the <textarea> gets taller if there is lot's of text.
The thing to do is to create an invisible<div>, for each keydown in the <input>, take its content and puts it into the <div>, and check its width is bigger than the <input>'s one.
The HTML
<form>
<input>
<div></div>
</form>
The CSS where we set the same font-size for the <input> and the <div> and hide the <div> (with position: absolute because we need it's width and we don't want it to change the layout)
form > * {
font-size: 22px
}
form > input {
width: 150px;
font-size: 18px;
}
form > div {
position: absolute;
left: -10000px;
}
And the JavaScript (with jQuery here)
var $form = $('form')
, $input = $('input', $form)
, $autoResize = $('div', $form)
, $both = $input.add($autoResize)
, fontSize = parseInt($input.css('font-size'), 10)
$input.on('keydown', function() {
$autoResize.html(this.value.replace(/&/g, '&')
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/ {2,}/g, function(spaces) {
// Change the spaces to $nbsp; except the last one
for (var i = 1, fakeSpaces = '', space; space = spaces[i++];) {
fakeSpaces += ' '
}
return fakeSpaces + ' '
})
)
// We add 10px to be sure it doesn't stick to the edges
if ($autoResize.outerWidth() >= $input.outerWidth() - 10) {
do {
$both.css('font-size', --fontSize)
} while ($autoResize.outerWidth() >= $input.outerWidth() && fontSize > 10)
// 10px is the smallest font-size accepted
if (fontSize === 10) {
$input.off('keydown')
}
}
})
Here is the jsFiddle.
You must use JavaScript to count how much characters've been typed already (I believe with .change() in jQuery) and change the font-size accordingly.
Yes,I think what #somebody is in trouble is doing is what they are doing in here.
Calculate how many letters will fit into the box - you know the width of the textbox. You know the font-size & padding that is being given here. So you know how many letters can be typed in the textbox before it overflows( not exactly) .
Or you can just type random letters & see how many can fit ! :)
Well, if you have time, you can as well dive into the events being fired when you keydown on the email address text box. You will learn a lot!
I have a parent element (e.g. a div) which surrounds some dynamic content. I would like the parent div to fully contain the child elements in as many circumstances as possible.
One problem is child elements with negative margin settings, which cause the child element to be displayed outside of the parent element (and also cause the parent element not to be of the desired size).
So
Is there any css trick that can be applied to the parent in order to suppress the negative margins in the child elements (e.g. without having to modify the styles on the child).
Failing that, is there anyway to detect via javascript whether a particular element has overflowing content? (and in which direction and to what degree the content is overflowing?)
Did you try to put a class to the parent like:
.parentDiv > * {
margin:0 !important;
}
To have the parent with the desired height, you need to set some css too:
.parentDiv{
overflow:hidden;
position:relative;
background:#DFE;
padding:5px;
}
There is a javascript method of handling this, but it's certainly not as clean as #Mic's CSS solution. I haven't completely tested this, and you may need to add some support for various padding/margin adjustments, but it would get somebody started if a JS-solution was the only option. Using prototype.js (jquery would be similar, but plain javascript will be very.. stretchy):
function checkOverflow (child) {
child = $(child);
if (child.descendants().any()) {
child.getElementsBySelector("> *").each(function(e) {
checkOverflow(e);
});
}
var parent = child.up();
var child_left = child.cumulativeOffset()['left'], child_top = child.cumulativeOffset()['top'];
var child_height = child.getDimensions()['height'], child_width = child.getDimensions()['width'];
var parent_left = parent.cumulativeOffset()['left'], parent_top = parent.cumulativeOffset()['top'];
var parent_height = parent.getDimensions()['height'], parent_width = parent.getDimensions()['width'];
if (child_top < parent_top) {
if (child_left < parent_left) {
// adjust element style here
} else if (child_left > parent_left + parent_width) {
// adjust element style here
}
} else if (child_top > parent_top + parent_height) {
if (child_left < parent_left) {
// adjust element style here
} else if (child_left > parent_left + parent_width) {
// adjust element style here
}
}
}
My general feeling, though, is that you should only do this if it can't be explicitly done through CSS.
My accordion is working properly, but I'm having a JS issue that are prohibiting it from displaying correctly.
http://jsfiddle.net/frEWQ/4/
The JS is not applying .ui-corners-all to the H3 after the "kwick" div below it has finished collapsing, giving an odd cut-off border after the animation
Any suggestions?
Thanks
// find elements to show and hide
var toShow = clicked.next(),
toHide = this.active.next(),
data = {
options: o,
newHeader: clickedIsActive && o.collapsible ? $([]) : clicked,
oldHeader: this.active,
newContent: clickedIsActive && o.collapsible ? $([]) : toShow,
oldContent: toHide
},
down = this.headers.index( this.active[0] ) > this.headers.index( clicked[0] );
this.active = clickedIsActive ? $([]) : clicked;
this._toggle(toShow, toHide, data, clickedIsActive, down);
// switch classes
this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all")
.find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header);
if (!clickedIsActive) {
clicked.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top")
.find(".ui-icon").removeClass(o.icons.header).addClass(o.icons.headerSelected);
clicked.next().addClass('ui-accordion-content-active');
}
return;
Updated:
You could modify the source, but that isn't generally a good idea.
Because it's expecting that specific format you may need to do something tricky with CSS to avoid that flicker.
How about have full 20px border-radius on all corners of the h3 at all times, even when the element is expanded.
Have the content use some styles like the following:
padding-top:20px; position:relative; top:-20px; or something similar that will pad 20px and then correct the position by pulling it back up. That way, when it expands it's actually overlapping the h3 bottom corners. If that didn't work padding-top:20px; margin-top:-20px; might.
In my mind this works. I'd try it on your jfiddle post but you haven't put the css source into the css frame.