How to calculate width of text using javascript? - javascript

How to get the width of the text.
var e=document.createElement('span');
e.style.fontSize = scope.fontsize;
e.innerHTML = "test";
console.log(e.offsetWidth);
Width always comes as 0

It seems like you have to append the created element to the document.
var e=document.createElement('span');
document.body.appendChild(e);
e.style.fontSize = 14;
e.innerHTML = "test";
console.log(e.offsetWidth);
e.remove();
Output: 23
Hiding the element does not work ether.
e.style.display= "none";
Output: 0
To "hide it" you could add a CSS like that. But with the added remove() it will likely not show up anyway. But adding position:absolute; is a good idea, since this will prevent flickering of the rest of the html content.
position:absolute;
margin-left:-1000em;

Related

Why does my css animation keep restarting when I add new elements with animation?

So when I click a button i append some html to the dom which gets animated, when I press the button again more html gets appended to the dom and gets animated.. My issue is that every element that i've appended always gets animated when i press the button. I want it to only get animated once, is this possible without using javascript to add and remove classes ?
.additional-text{
animation:fadein 4s;
}
#keyframes fadein {
from {
opacity: 0;
}
to {
opacity: 1
}
}
the Div that gets appended has the additional-text class.
https://jsfiddle.net/t7ykv86r/
The reason is because you're using innerHTML to update the DOM which means you convert an entire section of the DOM to string, add another DOM string to it, then convert back and render, which rerenders that entire section.
You should create and append nodes instead.
function addMoreText(){
var text = document.createElement('div')
text.classList.add('additional-text');
text.innerHTML = '<p>Even More of my text</p>';
var textEle = document.getElementsByClassName('text')[0];
textEle.appendChild(text)
}
See Fiddle.
Another workaround you may try:
var button = document.querySelector("button");
let count = 0;
button.addEventListener("click", addMoreText);
function addMoreText(){
count += 1
var text = "<div class=`${count > 1 ? null : 'additional-text'}`><p>More of my text</p><p>Even More of my text</p></div>"
var textEle = document.getElementsByClassName('text')[0];
textEle.innerHTML += text;
}

How to position a div next to element with absolute position?

I am trying to create a div that can be attached to an element whenever user hover to the link
I have many links and my codes look like the following.
for loops to create many links
codes....
link.href='#';
link.innerHTML = 'test'
link.onmouseover = OnHover;
codes....
function OnHover(){
var position;
var div = document.createElement('div');
div.className='testdiv';
div.innerHTML = 'test';
position=$(div).position();
div.style.top = position['top'] + 15 + 'px';
$(this).prepend(div);
}
link element1
link element2
----
| | //add new div when hover link element2
----
link element2
link element3
my css
.testdiv{
position:absolute;
}
I want to add a new div everytime the user hover to my link and position on the left top of the element.
My code would position all the div on top instead of every element.
Are there anyway to do this? Thanks so much!
Without seeing your other JavaScript/markup I can make the following observations:
You need to set position:absolute on your new div before top will do anything.
You need to make sure link is non-position:static.
Non-dynamic styles like the above should be in your CSS, not JS.
Positioning absolutely means you shouldn't need to use $(div).position()
You're using a mix of jQuery and pure JavaScript which looks a little odd :)
JS
function OnHover() {
var position;
var div = $('<div></div>');
div.addClass('testdiv');
div.html('test');
div.css('top', 15);
$(this).prepend(div);
}
CSS
.testdiv {
position:absolute;
}
a.testanchor {
position:relative;
}

I can't figure out how to add an text dynamically to the screen in a specific "X,Y" location

I need to add a text to the screen in a specific location. does anyone have any sample code they can post??
Example: lets say I had to add "This is a text" to 50px left and 100px top but I had to do it dynamically. how could I do it??
Thanks!
PS I'm VERY new to Javascript :]
Here is how to do that with JavaScript:
// Create an HTML paragraph to hold the text
var p = document.createElement('p');
// Add some text to it
p.innerHTML = "Some text <span>and markup</span>";
// Give it position: absolute so you can position by x,y
p.style.position = 'absolute';
// Define position
p.style.left = '50px';
p.style.top = '100px';
// Add it to the body
document.body.appendChild(p);

Javascript Custom Alert Box with Image alignment

I Have created Custom Alert Box in Javascript . I Have added text with images. but It is not align proberly. It came some thing like this.
I am trying to add the correct mark and text with same line, how can I achieve this. can anyone please help me. I have added my Custom alert box Function below.
function createCustomAlert(txt, string_url,fd) {
// shortcut reference to the document object
d = document;
// if the modalContainer object already exists in the DOM, bail out.
if (d.getElementById("modalContainer")) return;
// create the modalContainer div as a child of the BODY element
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "modalContainer";
// make sure its as tall as it needs to be to overlay all the content on the page
mObj.style.height = document.documentElement.scrollHeight + "px";
// create the DIV that will be the alert
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "alertBox";
// MSIE doesnt treat position:fixed correctly, so this compensates for positioning the alert
if (d.all && !window.opera) alertObj.style.top = document.documentElement.scrollTop + "px";
// center the alert box
alertObj.style.left = (d.documentElement.scrollWidth - alertObj.offsetWidth) / 2 + "px";
// create an H1 element as the title bar
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode(ALERT_TITLE));
btn2 = alertObj.appendChild(d.createElement("img"));
btn2.id = "fd";
btn2.src = fd;
// create a paragraph element to contain the txt argument
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = txt;
// create an anchor element to use as the confirmation button.
//btn = alertObj.appendChild(d.createElement("a"));
//btn.id = "closeBtn";
//btn.appendChild(d.createTextNode(ALERT_BUTTON_TEXT));
//btn.href = "";
btn = alertObj.appendChild(d.createElement("img"));
btn.id = "closeBtn";
btn.src = 'new-go-next2.png';
btn.href="#ss";
//btn.height="30px";
//btn.width="30px";
//btn.href="#";
// set up the onclick event to remove the alert when the anchor is clicked
btn.onclick = function () { removeCustomAlert(); window.location = string_url; return false; }
}
well yes creating a table would be a great approach to solve your problems , btw u can also try some internal divs with proper position anf the element having correct float attribute
Rather creating div element create table with two Columns. First of which will contain 'Image' for OK and Second one will contain your 'Text'.
Check if this helps.

JavaScript - Visible Text of a DIV

----------------------------------------------------
| This is my text inside a div and I want the overf|low of the text to be cut
----------------------------------------------------
Please note that I want the overflow to be removed, so the CSS ellipsis property would not work for me. So basically, I want that the text above to appear like this:
----------------------------------------------------
| This is my text inside a div and I want the overf|
----------------------------------------------------
How is this possible with pure JavaScript?
EDIT
I need a JavaScript function to crop the text because I need to count the characters of the visible text.
Okay, I didn't see the addendum to the question. Although I had previously said it wasn't possible to do this using JavaScript and a font that isn't fixed-width... it actually is possible!
You can wrap each individual character in a <span>, and find the first <span> that is outside the bounds of the parent. Something like:
function countVisibleCharacters(element) {
var text = element.firstChild.nodeValue;
var r = 0;
element.removeChild(element.firstChild);
for(var i = 0; i < text.length; i++) {
var newNode = document.createElement('span');
newNode.appendChild(document.createTextNode(text.charAt(i)));
element.appendChild(newNode);
if(newNode.offsetLeft < element.offsetWidth) {
r++;
}
}
return r;
}
Here's a demo.
You can do this with Javascript. Here is a function that counts the number of visible characters in an element, regardless of external css sheets and inline styles applied to the element. I've only tested it in Chrome, but I think it is cross browser friendly:
function count_visible(el){
var padding, em, numc;
var text = el.firstChild.data;
var max = el.clientWidth;
var tmp = document.createElement('span');
var node = document.createTextNode();
tmp.appendChild(node);
document.body.appendChild(tmp);
if(getComputedStyle)
tmp.style.cssText = getComputedStyle(el, null).cssText;
else if(el.currentStyle)
tmp.style.cssText = el.currentStyle.cssText;
tmp.style.position = 'absolute';
tmp.style.overflow = 'visible';
tmp.style.width = 'auto';
// Estimate number of characters that can fit.
padding = tmp.style.padding;
tmp.style.padding = '0';
tmp.innerHTML = 'M';
el.parentNode.appendChild(tmp);
em = tmp.clientWidth;
tmp.style.padding = padding;
numc = Math.floor(max/em);
var width = tmp.clientWidth;
// Only one of the following loops will iterate more than one time
// Depending on if we overestimated or underestimated.
// Add characters until we reach overflow width
while(width < max && numc <= text.length){
node.nodeValue = text.substring(0, ++numc);
width = tmp.clientWidth;
}
// Remove characters until we no longer have overflow
while(width > max && numc){
node.nodeValue = text.substring(0, --numc);
width = tmp.clientWidth;
}
// Remove temporary div
document.body.removeChild(tmp);
return numc;
}
JSFiddle Example
You're trying to force a CSS problem into JavaScript. Put the hammer away and get out a screwdriver. http://en.wiktionary.org/wiki/if_all_you_have_is_a_hammer,_everything_looks_like_a_nail
Solving the answer of character count is probably irrelevant if you take a step back. The last character could be only partially visible, and character count is drastically different given font size changes, the difference of width between W an i, etc. Probably the div's width is more important than the character count in the true problem.
If you're still stuck on figuring out the characters visible, put a span inside the div around the text, use the css provided in other answers to this question, and then in JavaScript trim one character at a time off the string until the span's width is less than the div's width. And then watch as your browser freezes for a few seconds every time you do that to a big paragraph.
try this, it requires a fixed width if that is ok with you: http://jsfiddle.net/timrpeterson/qvZKw/20/
HTML:
<div class="col">This is my text inside a div and I want the overf|low of the text to be cut</div>
CSS:
.col {
width:120px;
overflow: hidden;
white-space:nowrap;
}​
.col { width:40px; overflow: hidden; white-space:nowrap; }
White-space: nowrap; is needed when the content has spaces.
Either way, long words in single lines do not appear. http://jsfiddle.net/h6Bhb/

Categories

Resources