How to set styling of div based on another div using Javascript? - javascript

i have a unique case here. So i have 2 divs, one on the left and one on right. How can i make it so that if the height of left div exceeds the height of the div on right, the function should make the heights equal and hide any text for the left div. So if i calculate the offsetheight on load and for one on right is 443 px and one on left is 583 px, it should make both heights equal and height the rest 140px of data of left one.
I created a pen
var text = document.getElementById('overflow_text')
function mounted() {
var toggleBtn = document.getElementById('toggle_text')
var offsetDiv = document.getElementById('offset_height')
var offsetDivHeight = offsetDiv.offsetHeight + 'px'
var textHeight = text.offsetHeight + 'px'
console.log(textHeight)
console.log(offsetDivHeight)
if (textHeight > offsetHeight) {
text.style.maxHeight = offsetDivHeight
text.style.overflow = 'hidden'
text.style.textOverflow = 'ellipsis'
text.style.whiteSpace = 'nowrap'
}
}
#toggle_text {
cursor: pointer;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet" />
<body onLoad='mounted()'>
<div class="container">
<div class="row">
<div class="col-md-6">
<p id='overflow_text' class="readMore">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus
vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum.
Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec
congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis.
Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta. Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas
vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas
vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas
vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec</p>
<span onClick="myFunction()" id="toggle_text">Read More</span>
</div>
<div class="col-md-6">
<p id="offset_height">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus
vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum.
Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est,Donec vitae dui
eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae
scelerisque enim ligula venenatis dolor. Maecenas nisl estDonec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scelerisque enim ligula venenatis dolor. Maecenas nisl est </p>
</div>
</div>
</div>
</body>
So if you check the console, you will see what the heights of both divs are onLoad. Not sure how i can set the CSS through Javascript. Thank you in advance.
If any one has any other ideas on how to achieve this, i am open to suggestions.

The solution is a bit tricky, since you cannot simply use textOverflow: ellipsis css property if your text has multiple lines.
First we set height of the left text container to the height of the right which is smaller. Then we have to shrink the number of words displayed inside the left container. We remove words from the end of the container until container's scrollHeight is smaller or equal to the container's height.
In this way we know that the container has only as much words as it's able to display with restriction that it's no taller than the right container.
The drawback is that we remove overflowing words from the element so you're no longer able to get original content from this container.
function mounted() {
var leftContainer = document.getElementById('overflow_text')
var rightContainer = document.getElementById('offset_height')
var rightOffsetHeight = rightContainer.offsetHeight;
var leftOffsetHeight = leftContainer.offsetHeight;
if (leftOffsetHeight > rightOffsetHeight) {
leftContainer.style.height = rightOffsetHeight + "px"
var wordArray = leftContainer.innerHTML.split(' ');
while(leftContainer.scrollHeight > leftContainer.offsetHeight) {
wordArray.pop();
leftContainer.innerHTML = wordArray.join(' ') + '...';
}
}
}

Your if statement needs to use the variable name, offsetDivHeight.

if (textHeight > offsetHeight)
offsetHeight is never defined. Do you mean offsetDivHeight?
text.style.whiteSpace = 'nowrap'
If you do this, all of the text in the div will be confined to one line.
Demo with these changes made.

Related

Sliding text from under image

I need to show txt nicely sliding from under image after click. When user will click on other image, previous text have to slide out (not be vissible).
I am not good in javascript at all. Now I have something like this:
.html
<img src="image.jpg" width="100%" height="100px;">
<div class="slidingDiv">
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc venenatis auctor quam eget imperdiet. Vestibulum et nibh sit amet lectus mattis rutrum. Nam blandit vel massa eu laoreet. Etiam quam eros, iaculis in ornare viverra, gravida eu justo. Fusce nisi tortor, ornare et metus a, consequat sollicitudin mi. Nulla ipsum erat, ultricies semper ipsum sit amet, aliquet finibus ipsum. Fusce sodales lacus eget quam ullamcorper, mollis rhoncus lectus ullamcorper. Fusce tempor metus vel tincidunt condimentum. Fusce nunc risus, vehicula a cursus sit amet, vestibulum pretium felis. Praesent ex dolor, porta id sollicitudin non, venenatis ut ante. Maecenas porta velit augue, vel suscipit neque commodo et. Aenean ac dolor ac neque tristique porta. Ut neque diam, porta ut diam sit amet, vulputate auctor justo.</div>
</div>
<img src="image.jpg" width="100%" height="100px;">
<div class="slidingDiv">
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nunc venenatis auctor quam eget imperdiet. Vestibulum et nibh sit amet lectus mattis rutrum. Nam blandit vel massa eu laoreet. Etiam quam eros, iaculis in ornare viverra, gravida eu justo. Fusce nisi tortor, ornare et metus a, consequat sollicitudin mi. Nulla ipsum erat, ultricies semper ipsum sit amet, aliquet finibus ipsum. Fusce sodales lacus eget quam ullamcorper, mollis rhoncus lectus ullamcorper. Fusce tempor metus vel tincidunt condimentum. Fusce nunc risus, vehicula a cursus sit amet, vestibulum pretium felis. Praesent ex dolor, porta id sollicitudin non, venenatis ut ante. Maecenas porta velit augue, vel suscipit neque commodo et. Aenean ac dolor ac neque tristique porta. Ut neque diam, porta ut diam sit amet, vulputate auctor justo.</div>
</div>
.js
$(document).ready(function() {
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function() {
var isvisible = $(this).next('.slidingDiv').is(':visible');
if ( isvisible ) {
$(this).next('.slidingDiv').hide();
} else{
$(this).next('.slidingDiv').show();
}
});
});
https://jsfiddle.net/Elfiszcze/49vd6d6k/2/
Could someone help me with this one?
When using jquery hide() and show() you can set the parameter duration that will be used in animation duration, see jquery docs. For example, 500 miliseconds:
$(document).ready(function() {
$(".slidingDiv").hide();
$(".show_hide").show();
$('.show_hide').click(function() {
//hide all sliding divs
var arrayLikeOfSlidingDivs = $('.slidingDiv');
arrayLikeOfSlidingDivs.each(function(){
if ($(this).is(':visible')){
$(this).hide(500);
}
});
var isvisible = $(this).next('.slidingDiv').is(':visible');
if ( isvisible ) {
$(this).next('.slidingDiv').hide(500);
} else{
$(this).next('.slidingDiv').show(500);
}
});
});

Scroll to newly added variable height div

I am trying to figure out how to have a scrollable div scroll to the top of the most recently appended child div.
The html of the chatbox is as follows
<div class="character-chat-log">
<div class="character-chat-message"><strong>Test 1:</strong> test</div>
<div class="character-chat-message"><strong>Test 1:</strong> test</div>
<div class="character-chat-message"><strong>Test 1:</strong> hey</div>
<div class="character-chat-message"><strong>Test 1:</strong> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam ac dictum est. Ut auctor feugiat lectus, consectetur adipiscing lacus scelerisque eleifend. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Sed dignissim, tortor sit amet feugiat feugiat, ante urna luctus est, ut varius velit diam sed sem. Etiam ut eleifend risus. Maecenas vulputate arcu ipsum, ut tempus lectus pulvinar non. Donec non tellus sed diam semper tempus et eget eros. Mauris quis auctor lorem, non sodales urna. Ut dui dolor, ultricies sit amet lacinia in, ultrices eu mauris. Donec eros tellus, laoreet sagittis hendrerit id, scelerisque id mi. Praesent fringilla ligula id suscipit malesuada. Vivamus risus magna, lobortis a congue sit amet, consequat eget lorem. Vestibulum imperdiet ultricies rutrum. Donec a blandit enim, nec euismod ante. Phasellus dignissim molestie urna.</div>
</div>
Currently I am trying to scroll to the top of the latest "character-chat-message" as follows:
var newMessage = $(
'<div class="character-chat-message"><strong>'
+ sender
+ ':</strong> '
+ messageText
+ '</div>').appendTo(_messageBoxes[sender]);
_messageBoxes[sender].scrollTop(newMessage.position());
However this of course does not work at all.
It sounds like you're doing something similar to this question
Is that right?

link for max characters in javascript not working

Ive got a js that runs to see if a maximum amount of characters is reached. Its got text along with href, but when the max amount of characters is reached, the link doesnt work and converts it to just text. When the limit of less then 580 characters, link works. When it does reach the limit, the read more link does work. Any advice or help please and thanks
$(document).ready(function () {
var stylistText = $('#stylistText');
var stylistText2 = document.getElementById("stylistText").innerHTML;
var countActualText = stylistText2.valueOf().length;
var maxLength = 580;
var aElement = document.createElement('a');
var linkText = document.createTextNode(" ...Read more");
aElement.appendChild(linkText);
aElement.href = "#";
if (countActualText > maxLength) {
stylistText.text(stylistText.text().substring(0, 580));
stylistText.append(aElement);
}
});
here is the html
<div class="stylistInfo">
<img id="stylistPhoto" src="images/Test.jpg" alt="peekaboo beans stylist" />
<p id="stylistText">
This is supposed to be a link Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet.Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis nec mauris odio. Sed varius, felis eget rutrum scelerisque, enim ligula porta nulla, id rhoncus orci nisi at nunc. Fusce cursus, libero a sagittis viverra, arcu eros luctus arcu, sit amet euismod sapien purus quis nisl. Praesent aliquam aliquam ante ornare pulvinar. Mauris ultrices dictum quam, at ornare dui blandit id. Sed erat elit, fringilla quis diam at, euismod rhoncus massa. Curabitur at arcu nisl. Nullam tincidunt lacus sapien, sed porttitor odio sodales sit amet. Nunc tincidunt nisi et nulla aliquam cras amet.
</p>
</div>
Change stylistText.text(stylistText.text().substring(0, 580));
to stylistText.html(stylistText.html().substring(0, 580));
However, truncating a block of text that contains HTML may cause other problems, especially if the truncation occurs in the middle of an element. I would recommend rethinking your whole strategy on this.

Get the invisible text with JavaScript

Suppose we have the following code:
<div id="test" style="width:200px; height: 200px; overflow: hidden;">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus
ipsum diam, cursus ornare eleifend quis, posuere id sapien. Vestibulum
et mattis augue. Nulla facilisi. Sed rhoncus facilisis commodo. Sed mattis
commodo lorem, quis varius est facilisis eget. Integer at nunc metus.
Fusce augue odio, elementum et hendrerit vitae, malesuada at urna.</p>
<p>Consectetur adipiscing elit. Vivamus lorem ipsum dolor sit amet,
ipsum diam, cursus ornare eleifend quis, posuere id sapien. Vestibulum
et mattis augue. Nulla facilisi. Sed rhoncus facilisis commodo. Sed mattis
commodo lorem, quis varius est facilisis eget. Integer at nunc metus.
Fusce augue odio, elementum et hendrerit vitae, malesuada at urna.</p>
<p>Sed rhoncus facilisis commodo. Sed mattis lorem ipsum dolor sit amet,
consectetur adipiscing elit. Vivamus ipsum diam, cursus ornare eleifend
quis, posuere id sapien. Vestibulum et mattis augue. Nulla facilisi.
commodo lorem, quis varius est facilisis eget. Integer at nunc metus.
Fusce augue odio, elementum et hendrerit vitae, malesuada at urna.</p>
</div>
The result would be a clipped text.
Is there some way to get invisible text as a substring?
I tried
$("#test :hidden").text();
and
$('#test').children(":hidden").text()
without success.
I'm trying to show pages of text without scrolling. I have a large amount of text (html formatted) and a fixed size div (the text page). I would like to paginate the text on it, just showing one page of text each time.
There is a good answer on this topic already, it provides the javascript you'd need to do this. Like the respondent there though, I would say find another way to do this if you can.
You could use a mono-spaced font like Lucida Console or Courier New and split the string based on a static number of characters that fit in the content area.

How can I select the first word of every line of a block of text?

I'm trying to select each first word, to wrap it in a specific span.
Lorem ipsum dolor sit amet,
consectetur adipiscing elit. Cras
sagittis nunc non nisi venenatis
auctor. Aliquam consectetur pretium
sapien, eget congue purus egestas nec.
Maecenas sed purus ut turpis varius
dictum. Praesent a nunc ipsum, id
mattis odio. Donec rhoncus posuere
bibendum. Fusce nulla elit, laoreet
non posuere.
If this is the text, the script should select Lorem, Aliquam, varius and nulla.
You can do this, by using JavaScript to wrap every word in the paragraph in its own span, and then walking through the spans finding out what their actual position on the page is, and then applying your style changes to the spans whose Y position is greater than the preceding span. (Best do it beginning-to-end, though, as earlier ones may well affect the wrapping of latter ones.) But it's going to be a lot of work for the browser, and you'll have to repeat it each time the window is resized, so the effect will have to be worth the cost.
Something like this (used jQuery as you've listed the jquery tag on your question):
jQuery(function($) {
var lasty;
var $target = $('#target');
$target.html(
"<span>" +
$target.text().split(/\s/).join("</span> <span>") +
"</span>");
lasty = -1;
$target.find('span').each(function() {
var $this = $(this),
top = $this.position().top;
if (top > lasty) {
$this.css("fontWeight", "bold");
lasty = top;
}
});
});
<div id='target' style='width: 20em'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
Naturally that's making a huge set of assumptions (that all whitespace should be replaced with a single space, that there's no markup in the text, probably others). But you get the idea.
Here's a version that handles window resize, 50ms after the last resize event occurs (so we're not doing it interim) and with Gaby's suggestion (below) that we unbold at the start of the resize:
jQuery(function($) {
var resizeTriggerHandle = 0;
// Do it on load
boldFirstWord('#target');
// Do it 100ms after the end of a resize operation,
// because it's *expensive*
$(window).resize(function() {
if (resizeTriggerHandle != 0) {
clearTimeout(resizeTriggerHandle);
}
unboldFirstWord('#target');
resizeTriggerHandle = setTimeout(function() {
resizeTriggerHandle = 0;
boldFirstWord('#target');
}, 50);
});
function boldFirstWord(selector) {
var lasty;
// Break into spans if not already done;
// if already done, remove any previous bold
var $target = $(selector);
if (!$target.data('spanned')) {
$target.html(
"<span>" +
$target.text().split(/\s/).join("</span> <span>") +
"</span>");
$target.data('spanned', true);
}
else {
unboldFirstWord($target);
}
// Apply bold to first span of each new line
lasty = -1;
$target.find('span').each(function() {
var $this = $(this),
top = $this.position().top;
if (top > lasty) {
$this.css("fontWeight", "bold");
lasty = top;
}
});
$target.data('bolded', true);
}
function unboldFirstWord(selector) {
var $target = selector.jquery ? selector : $(selector);
if ($target.data('spanned') && $target.data('bolded')) {
$target.find('span').css("fontWeight", "normal");
$target.data('bolded', false);
}
}
});
<div id='target'>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor. Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum. Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
Try this:
$(function() {
$('p').each(function() {
var text_splited = $(this).text().split(" ");
$(this).html("<strong>"+text_splited.shift()+"</strong> "+text_splited.join(" "));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras sagittis nunc non nisi venenatis auctor.</p>
<p>Aliquam consectetur pretium sapien, eget congue purus egestas nec. Maecenas sed purus ut turpis varius dictum.</p>
<p>Praesent a nunc ipsum, id mattis odio. Donec rhoncus posuere bibendum. Fusce nulla elit, laoreet non posuere.</p>
To bold every first word of a <p> tag, including whitespace after the initial <p>, use some regular expressions:
$('p').each(function(){
var me = $(this);
me.html( me.text().replace(/(^\w+|\s+\w+)/,'<strong>$1</strong>') );
});

Categories

Resources