I need something that will change the style of a div when you scroll to a specific element
Example:
In my header i have the texts:
1) Home
2) Text2
3) Text3
4) Text4
When on top i want the "Home" to be white and all the others blue
When on paragraph 1 i want the "Text2" white and all the other blue
When on paragraph 2 i want the "Text3" white and all the other blue
When on paragraph 3 i want the "Text4" white and all the other blue
When below "Text4" i want the "Home" to be white and all the others blue
PS: "Text2","Text3" and "Text4" will have nothing else in betwheen
I'd go with waypoints or with skrollr. There are plenty of tutorials about skrollr so dont worry.
You can do something like this
Use scroll() to listen scroll event
Get the scroll top value by using scrollTop()
DEMO :
$(window).scroll(function() {
$('#div2').css('color', $(this).scrollTop() > 390 ? 'red' : 'blue');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id=main style="height:1000px">
<div id=div2 style="margin-top:500px">element</div>
</div>
This toggles the color of any header text at the point a matching element comes into view (or leaves) :
Demo
$(function() {
var gate = $(window),
bar = $('header'),
title = bar.find('span'),
element = $('.element'),
viewin, viewout;
gate.on('load resize', function() {
viewin = []; viewout = [];
element.each(function() {
var placement = $(this).offset().top-gate.height(),
dimension = $(this).outerHeight();
viewin.push(placement);
viewout.push(placement+dimension);
});
})
.scroll(function() {
var location = gate.scrollTop();
element.each(function(i) {
var option = title.eq(i), white = option.hasClass('white');
if (location > viewin[i] && location <= viewout[i]) {
if (!white) option.addClass('white');
}
else if (white) option.removeClass('white');
});
});
});
Comments below are no longer very relevant because they are discussing an earlier stage.
Animating colors does not work unless you include a library for animating colors.
jQuery does not animate colors by default.
So for color-animation you must include library like JQuery UI, but it is large for just using color-animation.
Instead i would suggest you to use Bitstorm:ColorLibrary, it's just 2.7kb in size.
JSFiddle : DEMO
$(document).ready(function(){
var top = document.getElementById("css_text").scrollHeight; // top position of '#css_text'
alert("Top position of #CSS_TEXT : " + top);
var calcu = top - 20;
$(window).scroll( function(){
var pos = $(window).scrollTop();
if(pos >= calcu)
{
$("#css_text").animate({"color":"red","opacity":"1"},2000);
}
});
});
#css_text
{
opacity:0;
color:blue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="http://www.bitstorm.org/jquery/color-animation/jquery.animate-colors-min.js"></script>
<h1>HTML Ipsum Presents</h1>
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.</p>
<h2>Header Level 2</h2>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.</p></blockquote>
<h3>Header Level 3</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ul>
<pre id="css_text"><code>
#header h1 a {
display: block;
width: 300px;
height: 80px;
}
</code></pre>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
<li>Vestibulum auctor dapibus neque.</li>
</ul>
Check the following jquery functions
scroll
scrollTop
offset
each
attr
Your code could look something like that:
( function( $ ) {
$(window).scroll(function(e){
var home = $('#home');
var switchPosition = $(window).scrollTop() + parseInt(home.css("top"))+30;
$('.text').each(function(){
if ( switchPosition > $(this).offset().top &&
$(this).attr('data-color') !== home.attr('data-color') ) {
home.css({color: $(this).attr('data-color')});
home.attr('data-color', $(this).attr('data-color') );
}
});
});
} )( jQuery );
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="home" style="font-weight: bold; color: blue; position: fixed; top: 20px; left: 20px;">HOME</div>
<div style="color: white; position: fixed; top: 170px; left: 20px;">scroll down...</div>
<div class="text" data-color="blue" style="background: #999; height: 500px"> </div>
<div class="text" data-color="red" style="background: #666; height: 500px"> </div>
<div class="text" data-color="white" style="background: #333; height: 1000px"> </div>
Related
I'm using Ajax to get comments. Comment text is treated as max-height:90px by default. When importing comments, I want to attach a link if the text length is longer than the parent element.
The code below doesn't work well.
It works imperfectly.
All comments have a link or only the first one.
Is there any right way?
$( document ).on('click' , '.view_comments' , function(){
let id = $(this).attr("id");
let content = $("#comment-post-"+id).val();
let last_cmt = $("ul#canvas-comments-"+id+" li:last").val();
$.ajax({
type:"GET",
url: "http://192.168.10.21/v1/server1/comment/view_comment.php",
data:{ enclosure: content, cmt: last_cmt },
success:function(html){
const result = JSON.parse(html);
if( result.length > 0 ){
let comment = '';
for( const item of result ){
const comment_list = comment_object( item );
comment += comment_list.get_html();
}
$("ul#canvas-comments-"+id).append(comment);
/************************************************
* # if comment overflown div.wts-comment-text *
************************************************/
const hasElement = $('*').is($(".wts-comment-text"));
if( hasElement === true ){
const parent = document.querySelector('.wts-comment-text');
if( isOverflown( parent ) ){
const sub_id = $(parent).attr("data-value");
$("#comment-option"+sub_id).html("<a href='#' data-value='"+sub_id+"' class='view-comment-details'><span>More...<span></a>");
}
}
$(this).html('More Comments');
}else if( result.length === 0 ){
console.log("zero");
$(this).html('Comments 0');
}
},
error: function( xhr ){
console.log(xhr.status+' '+xhr.statusText);
}
});
return false;
});
function isOverflown(e){
return e.scrollHeight > e.clientHeight;
}
var comment_object = function(data){
const id = data['comment_id'];
const user_id = data['user_id'];
const username = data['username'];
const date = data['date'];
const comment = data['comment'];
return {
get_html: function(){
return "<li value='"+id+"' class='wts-comment'><div class='wts-comment-left'><span class='wts-comment-author'>"+username+"</span><span class='wts-comment-date'>"+date+"</span></div><div class='wts-comment-text-wrapper'><input type='hidden' name='comment_id' value='"+id+"' /><div class='wts-comment-wrapper'><div class='wts-comment-rating-container'><div class='wts-rating-inner-wrapper'><div class='wts-comment-rating'><div class='wts-comment-rating-value'></div></div></div><div id='commentTextBox"+id+"' class='wts-comment-text'><p>"+comment+"</p></div><div class='wts-comment-action-icons'><div id='comment-option"+id+"' class='wts-comment-action-renderer'><a href='#' data-value='"+id+"' data-action='n-ack' class='cwt-link-cr view-comment-details'><span class='n-ack'>펼쳐보기<span></a></div></div></div></li>";
}
};
};
Based on this SO answer. You can check if the text is bigger than your container and append more link to your HTML.
$(document).ready(function() {
$('.comments .text').each(function() {
if ($(this)[0].scrollHeight > $(this).innerHeight()) {
$(this).parent().append('more...');
}
});
$('.comments').on('click', '.more', function(e) {
e.preventDefault();
$(this).parent().find('.text').css('height', 'auto');
$(this).css('display', 'none');
});
});
.comments {
width: 500px;
line-height: 30px;
border: solid 1px #ccc;
font-size: 20px;
margin-bottom: 35px;
}
.text {
height: 90px;
overflow-y: hidden;
}
.more {
height: 30px;
text-decoration: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<!-- First Comment -->
<div class="comments">
<div class="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce ullamcorper eleifend felis. Sed scelerisque tincidunt rutrum. Praesent efficitur nunc a mi vulputate, et lacinia leo mattis. Suspendisse nec dolor porttitor, egestas nisi et, egestas tellus.
</div>
</div>
<!-- Second Comment -->
<div class="comments">
<div class="text">
Lorem ipsum dolor sit amet.
</div>
</div>
<!-- Third Comment -->
<div class="comments">
<div class="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce ullamcorper eleifend felis. Sed scelerisque tincidunt rutrum. Praesent efficitur nunc a mi vulputate, et lacinia leo mattis. Suspendisse nec dolor porttitor, egestas nisi et, egestas tellus.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce ullamcorper eleifend felis. Sed scelerisque tincidunt rutrum. Praesent efficitur nunc a mi vulputate, et lacinia leo mattis. Suspendisse nec dolor porttitor, egestas nisi et, egestas tellus.
</div>
</div>
<!-- Fourth Comment -->
<div class="comments">
<div class="text">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Fusce ullamcorper eleifend felis.
</div>
</div>
I'm working on a multi-language project. I want to change all the used margin-left styles to margin-inline-start, after the direction of the <body> changed according to the selected language. how can I do it programmatically in javaScript?
You probably can try to loop through computed style, retrieve margin-left value, reset margin-left and then apply a margin-inline-start with the value of margin left.
here is the basic idea : (Live Demo at https://codepen.io/gc-nomade/pen/MWrGBjX?editors=1111 )
let allelements = document.querySelectorAll("body *");
for (i = 0; i < allelements.length; i++) {
let computedStyle = window.getComputedStyle(allelements[i]);
// look for
if (computedStyle.getPropertyValue("margin-left") != "0px") {
let valMargin = computedStyle.getPropertyValue("margin-left");
// let's see what's going on, if anything happens
console.log(
"found margin-left. value : " +
computedStyle.getPropertyValue("margin-left") +
" of " +
allelements[i].tagName
);
//reset
allelements[i].style.marginLeft = "auto";
// set/reset inline-start margin
allelements[i].style.marginInlineStart = valMargin;
}
}
body {
direction: rtl;
}
h1,
p,
code {
margin-left: 10em;
}
<h1>HTML Ipsum Presents</h1>
<p><strong>Pellentesque habitant morbi tristique</strong> senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. <em>Aenean ultricies mi vitae est.</em> Mauris placerat eleifend leo. Quisque sit amet est et sapien ullamcorper pharetra. Vestibulum erat wisi, condimentum sed, <code>commodo vitae</code>, ornare sit amet, wisi. Aenean fermentum, elit eget tincidunt condimentum, eros ipsum rutrum orci, sagittis tempus lacus enim ac dui. Donec non enim in turpis pulvinar facilisis. Ut felis.</p>
<h2>Header Level 2</h2>
<ol>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ol>
<blockquote><p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus magna. Cras in mi at felis aliquet congue. Ut a est eget ligula molestie gravida. Curabitur massa. Donec eleifend, libero at sagittis mollis, tellus est malesuada tellus, at luctus turpis elit sit amet quam. Vivamus pretium ornare est.</p></blockquote>
<h3>Header Level 3</h3>
<ul>
<li>Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</li>
<li>Aliquam tincidunt mauris eu risus.</li>
</ul>
<pre><code>
#header h1 a {
display: block;
width: 300px;
height: 80px;
}
</code></pre>
I'm not an developper, so that might not be the most effective way to do it.
But starting from here, you will probably find out that margin-right maybe needs to be reset too, and so floats....
If you use a flex or grid-layout, without margin , but justify/align , you will not have to bother about the direction / dir value of the document , the browser will follow it naturally ;)
This question already has answers here:
Toggle Read More/Read Less using Javascript?
(4 answers)
Closed 1 year ago.
I am referring this solution. The Change I want is Read More button should come at the end of the line as shown in pic
on load it should be only two lines with show more button in second line at the end
on show more it should expand and show entire text
on show less it should shrink back to two lines with button at the end of the line
function myFunction() {
let text = document.getElementById('overflow_text')
let toggle = document.getElementById('toggle_text')
if (text.style.overflow == 'visible') {
toggle.innerHTML = '..more'
text.style.overflow = 'hidden'
text.style.textOverflow = 'ellipsis'
text.style.whiteSpace = 'nowrap'
} else {
toggle.innerHTML = 'less'
text.style.overflow = 'visible'
text.style.textOverflow = 'string'
text.style.whiteSpace = 'normal'
}
}
.myClass {
height: 150px;
width : 500px;
}
#overflow_text {
white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
}
#toggle_text {
cursor: pointer;
}
.button_span{
border: black;
border-width: 1px;
border-color: black;
border-style: solid;
}
<div class="container">
<div class="row">
<div class="col-md-6 myClass">
<p id='overflow_text'>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.</p>
<span onClick="myFunction()" id="toggle_text" class="button_span">more</span>
</div>
</div>
</div>
I suggest including the "..." in the button, because the text does not "know" when it has run out of space.
CSS:
#mainContent{
position:relative;
line-height:1em;
overflow:hidden;
}
.showContent{
height: 2em;
}
.hideContent{
height: auto;
}
#moreButton{
position:absolute;
bottom:0;
right:0;
cursor:pointer;
background:white;
padding-left:4px;
}
HTML:
<div class="showContent" id="mainContent">
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s
<span id="moreButton" onclick="showMoreLess()">...more</span>
</div>
...and finally JS:
function showMoreLess(){
var mc = document.getElementById('mainContent');
var btn = document.getElementById('moreButton');
if (btn.innerHTML == '...more') {
mc.className = 'hideContent';
btn.innerHTML = '...less';
} else {
mc.className = 'showContent';
btn.innerHTML = '...more';
}
}
Please let me know if this helps!
I was hoping to prove how cool and easy AngularJS is with a small Accordion example, the whole thing is pretty simple, in my Controller I have an array and I have a ng-repeat where I bind some data and apply a css rule when the $index of the ng-repeat matches a scope variable. It's all simple stuff like so, here is my controller (I've reduced some of the text for this example).
$scope.paymentTypes = [
{name: 'Visa', text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ullamcorper ac sem non molestie. Mauris eu tempor nisi. Praesent vitae porta lectus. Maecenas risus eros, feugiat eget vehicula at!'},
{name: 'Master Card', text: 'Mauris eu tempor nisi. Praesent vitae porta lectus. Maecenas risus eros, feugiat eget vehicula at, scelerisque ac nisi. Nunc tristique, ipsum eu gravida dignissim, lacus turpis dapibus enim, ut viverra neque sem ac lectus. Sed sit amet auctor est. Nulla sit amet felis magna.'},
{name: 'Paypal', text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ullamcorper ac sem non molestie. Mauris eu tempor nisi. Praesent vitae porta lectus. Maecenas risus eros, feugiat eget vehicula at, scelerisque ac nisi. Nunc tristique, ipsum eu gravida dignissim, lacus turpis dapibus enim, ut viverra neque sem ac lectus. Sed sit amet auctor est. Nulla sit amet felis magna.'},
{name: 'Bitcoin', text: 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ullamcorper ac sem non molestie.'}];
$scope.selectedType = null;
$scope.togglePayments = function (index) {
if ($scope.selectedType === index) {
$scope.selectedType = null;
} else {
$scope.selectedType = index;
}
}
and here is my ng-repeat in my view...
<div data-ng-repeat="ptype in paymentTypes track by $index" data-ng-click="togglePayments($index)">
<div class="row u-padding-vert-s">
<div class="col-xs-6 payment-type" data-ng-bind="ptype.name"></div>
<div class="col-xs-6 text-right"><!-- put a logo here later --></div>
</div>
<div class="row u-slide-down" data-ng-hide="selectedType !== $index">
<div class="col-xs-12" data-ng-bind="ptype.text">
</div>
</div>
<div class="row">
<div class="col-xs-5 u-border-top-1"></div>
<div class="col-xs-2 toggle-tab text-center">
<span class="icon-ic_list_arrow_down"></span>
</div>
<div class="col-xs-5 u-border-top-1"></div>
</div>
</div>
and here is the css I have created to prove the sliding open and close animation:
.u-slide-down {
transition: .3s linear all;
overflow: hidden;
background: yellowgreen;
height: 200px;
}
.u-slide-down.ng-hide {
height: 0px;
}
Pretty cool, however this example relies on all hidden divs being the same height. In the real world I would prefer the hidden div to be flexible with its height and be more dynamic! As the content is different and may even contain HTML at some point. Now when I set my css to height: auto; in the .u-slide-down class the animation is lost. I don't want to have to write a directive for this as I want my example to be as simple as possible, so can anyone suggest what I can do to my CSS to allow dynamic heights and retain the animation? In the meantime, I'll try to put something together in https://jsbin.com... give me a sec!
I would like to create a read more link that would extend a paragraph already being shown to reveal the entire text on the same page. If this could be solves with HTML5 and CSS, I would like that, but I assume some type of script will be needed.
For example:
Example text
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam porttitor feugiat ipsum quis ullamcorper. Nullam vitae velit vitae tortor semper tempor ac vitae magna. Maecenas a ullamcorper neque. Aliquam vitae tortor luctus nisi rutrum eleifend non non leo.
Sed eleifend lectus id semper accumsan. Sed lobortis id ligula eget blandit. Integer interdum iaculis nunc, sed porttitor magna tincidunt in. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam lobortis accumsan tempor. Aliquam sollicitudin pulvinar est, quis convallis tellus.
Read More >>
I would like the normal text to be shown with the "Read More >>" link below, and then the bold text will be revealed after clicking the link.
I also want to have an image in the hidden section, would this be possible?
Thanks in advance.
A vanilla JS alternative:
The HTML:
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam porttitor feugiat ipsum quis ullamcorper. Nullam vitae velit vitae tortor semper tempor ac vitae magna. Maecenas a ullamcorper neque. Aliquam vitae tortor luctus nisi rutrum eleifend non non leo.</p>
<div id="more" style="display:none;">
<p>Sed eleifend lectus id semper accumsan. Sed lobortis id ligula eget blandit. Integer interdum iaculis nunc, sed porttitor magna tincidunt in. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam lobortis accumsan tempor. Aliquam sollicitudin pulvinar est, quis convallis tellus.</p>
<img..../>
</div>
Read More >>`
The JS:
function showMore(){
//removes the link
document.getElementById('link').parentElement.removeChild('link');
//shows the #more
document.getElementById('more').style.display = "block";
}
There is some really grateful plugins out there uses jquery.
Here is what i found
https://github.com/jedfoster/Readmore.js
The required markup for Readmore.js is also extremely lightweight and very simple. No need for complicated sets of div s or hardcoded class names, just call .readmore() on the element containing your block of text and Readmore.js takes care of the rest.
I created something easy to use
set a class to the content "div"
use "<!--more-->" to separate the click-to-display contents from the always visible contents
everything else will be taking care of by css and js
HTML:
<div class="m-more-less-content">
Lorem ipsum dolor sit amet, <!--more--> At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua.
</div>
See example here
I've created a jQuery/JS script that should do the trick:
JSFiddle: http://jsfiddle.net/Starfire1337/pL9ve/
HTML:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.4.3/jquery.min.js"></script>
<script src="/js/site.js"></script> // Notice the custom JS is included AFTER jQuery
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam porttitor feugiat ipsum quis ullamcorper. Nullam vitae velit vitae tortor semper tempor ac vitae magna. Maecenas a ullamcorper neque. Aliquam vitae tortor luctus nisi rutrum eleifend non non leo.</p>
Read More...
<div id="collapse" style="display:none">
<p>Sed eleifend lectus id semper accumsan. Sed lobortis id ligula eget blandit. Integer interdum iaculis nunc, sed porttitor magna tincidunt in. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam lobortis accumsan tempor. Aliquam sollicitudin pulvinar est, quis convallis tellus.</p>
</div>
and in /js/site.js:
$(document).ready(function () {
$('.nav-toggle').click(function () {
var collapse_content_selector = $(this).attr('href');
var toggle_switch = $(this);
$(collapse_content_selector).toggle(function () {
if ($(this).css('display') == 'none') {
toggle_switch.html('Show');
} else {
toggle_switch.html('Hide');
}
});
});
});
You can do it, change the property of CSS via Javascript.
element.style.display = 'block';
JS code
function read_more() {
document.getElementById('hidden-first').style.display = 'block';
}
document.getElementById('read-more').addEventListener('click', read_more);
See this code on JSfiddle
Yes it is ... this is just a small example http://jsfiddle.net/QDg4P/3/
<div>
<h1>Example text</h1>
<p >Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam porttitor feugiat ipsum quis ullamcorper. Nullam vitae velit vitae tortor semper tempor ac vitae magna. Maecenas a ullamcorper neque. Aliquam vitae tortor luctus nisi rutrum eleifend non non leo.</p> read more
<p id="example1" style="display:none; font-weight: bold"><img src="http://tux.crystalxp.net/png/kami23-flower-tux-4037.png"/>Sed eleifend lectus id semper accumsan. Sed lobortis id ligula eget blandit. Integer interdum iaculis nunc, sed porttitor magna tincidunt in. Interdum et malesuada fames ac ante ipsum primis in faucibus. Aliquam lobortis accumsan tempor. Aliquam sollicitudin pulvinar est, quis convallis tellus.</p>
<script>
function show(ele){
document.getElementById(ele).style.display = 'block';
}
</script>
Here's a pure HTML + CSS solution. You can style the "show more" checkbox using CSS to make it fit your needs, including hiding the checkbox part.
http://jsfiddle.net/T7eXL/
<div id="box">
<p>Lorem ipsummy</p>
<input type="checkbox" class="show-more"> Show more
<div class="more">
<p>Lorem</p>
</div>
</div>
.more {
display:none;
}
#box .show-more:checked + .more {
display:block;
}
after text put that code
<p><a onclick="javascript:ShowHide('HiddenDiv')">Read more</a></p>
<div class="mid" id="HiddenDiv" style="display: none;">
<font face="Arial" size="+2" color="#306Eff" align="right">YOUR REST OF THE TEXT HERE YOUR REST OF THE TEXT HERE
YOUR REST OF THE TEXT HERE YOUR REST OF THE TEXT HERE YOUR REST OF THE TEXT HERE YOUR REST OF THE TEXT HERE YOUR REST OF THE TEXT HERE YOUR REST OF THE TEXT HERE
</div>
<script type="text/javascript">// <![CDATA[
function ShowHide(divId)
{
if(document.getElementById(divId).style.display == 'none')
{
document.getElementById(divId).style.display='block';
}
else
{
document.getElementById(divId).style.display = 'none';
}
}
// ]]></script>
If you want something like this (have read more element after text) and you also have multiple dynamic elements:
Every month first 10 TB are are not charged. All other traffic... Read more
HTML&CSS:
<small class="truncate_string_multilines block-with-text" id="multiline_block" data-initial_value="Every month first 10 TB are are not charged. All other traffic (incoming and outgoing) is charged Read more">Every month first 10 TB are are not charged. All other traffic... Read more</small>
.block-with-text {
height: 4.2em;
}
small {
font-weight: 400;
font-size: 0.875rem;
display: inline-block;
line-height: 1.4;
}
JS&JQUERY
var initial_string = [], wordArray = '';
function ellipsizeTextBox(class_name) {
var el = document.getElementsByClassName(class_name);
for (i = 0, len = el.length; i < len; i++) {
initial_string[i] = el[i].innerHTML;
wordArray = el[i].innerHTML.split(' ');
while(el[i].scrollHeight > el[i].offsetHeight) {
wordArray.pop();
el[i].innerHTML = wordArray.join(' ') + '... ' + "" + moretext + "";
}
el[i].setAttribute("data-initial_value", initial_string[i]);
}
}
$("body").on("click",".morelink_multi", function(){
var this_element = $(this),
parent_of_link = $(this).parent();
if(this_element.hasClass("less")) {
this_element.removeClass("less");
this_element.html(moretext);
parent_of_link.addClass('block-with-text');
ellipsizeTextBox('truncate_string_multilines');
} else {
parent_of_link.removeClass('block-with-text');
parent_of_link.html('');
parent_of_link.html(parent_of_link.data('initial_value') + " <a href=\"#\" class='morelink_multi less'>"+ lesstext + "</a>");
}
});
More advanced version if your text is dynamic or coming from a database.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Add Read More Link</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
var maxLength = 300;
$(".show-read-more").each(function(){
var myStr = $(this).text();
if($.trim(myStr).length > maxLength){
var newStr = myStr.substring(0, maxLength);
var removedStr = myStr.substring(maxLength, $.trim(myStr).length);
$(this).empty().html(newStr);
$(this).append(' read more...');
$(this).append('<span class="more-text">' + removedStr + '</span>');
}
});
$(".read-more").click(function(){
$(this).siblings(".more-text").contents().unwrap();
$(this).remove();
});
});
</script>
<style>
.show-read-more .more-text{
display: none;
}
</style>
</head>
<body>
<p>This is a paragraph.</p>
<p>This is another paragraph.</p>
<p class="show-read-more">This is a very long paragraph...</p>
</body>
</html>
Refer https://www.w3schools.com/howto/howto_js_expanding_grid.asp
Another Vanilla HTML, javascript and css example if you want something like this, and changes the box on click of Box 2 or Box 3. At this moment in time I have put cross button on the expanded div only but you can put it back on click of the box again :
HTML :
<!-- The grid: three columns -->
<div class="row">
<div class="column" onclick="openTab('b1');" style="background: green;">Box 1</div>
<div class="column" onclick="openTab('b2');" style="background: blue;">Box 2</div>
<div class="column" onclick="openTab('b3');" style="background: red;">Box 3</div>
</div>
<!-- The expanding grid (hidden by default) -->
<div id="b1" class="containerTab" style="display: none; background: green">
<!-- If you want the ability to close the container, add a close button -->
<span onclick="this.parentElement.style.display='none'" class="closebtn">x</span>
<h2>Box 1</h2>
<p>Lorem ipsum..</p>
</div>
<div id="b2" class="containerTab" style="display: none; background: blue">
<span onclick="this.parentElement.style.display='none'" class="closebtn">x</span>
<h2>Box 2</h2>
<p>Lorem ipsum..</p>
</div>
<div id="b3" class="containerTab" style="display: none; background: red">
<span onclick="this.parentElement.style.display='none'" class="closebtn">x</span>
<h2>Box 3</h2>
<p>Lorem ipsum..</p>
</div>
CSS:
/* The grid: Three equal columns that floats next to each other */
.column {
float: left;
width: 33.33%;
padding: 50px;
text-align: center;
font-size: 25px;
cursor: pointer;
color: white;
}
.containerTab {
padding: 20px;
color: white;
}
/* Clear floats after the columns */
.row:after {
content: "";
display: table;
clear: both;
}
/* Closable button inside the image */
.closebtn {
float: right;
color: white;
font-size: 35px;
cursor: pointer;
}
JS:
// Hide all elements with class="containerTab", except for the one that matches the clickable grid column
function openTab(tabName) {
var i, x;
x = document.getElementsByClassName("containerTab");
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
document.getElementById(tabName).style.display = "block";
}