how to make a auto-scrolling horizontal scrollbar - javascript

I have a horizontal scrollable section in my page and i want its content to automatically scroll. i tried using the code for automatic vertical scroll but its not working.
code based from here how to make a scrollbar automatically move after sometime (JavaScript)
$(document).ready(function () {
var scrollHandler = null;
function autoScroll() {
clearInterval(scrollHandler);
scrollHandler = setInterval(function () {
var nextScroll = $('.menu').scrollLeft() + 20;
$('.menu').scrollLeft(nextScroll);
}, 1500);
}
autoScroll();
});
what do i need to do to make it work? i am a beginner so please explain. thanks.

Here you can see adapted code from the answer your code is based on.
$(document).ready(function() {
var scrollHandler = null;
function autoScroll () {
console.log("autoScroll");
clearInterval(scrollHandler);
scrollHandler = setInterval(function() {
var nextScroll = $('.scrolled').scrollLeft() + 20;
$('.scrolled').scrollLeft(nextScroll);
},500);
}
autoScroll();
});
.scrolled {
width: 50%;
height: auto;
overflow: scroll;
}
.inside {
width: 5000%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="scrolled">
<div class="inside" >
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Curabitur vitae diam non enim vestibulum interdum. Mauris dolor felis, sagittis at, luctus sed, aliquam non, tellus. Aliquam erat volutpat. Fusce consectetuer risus a nunc. Aliquam ornare wisi eu metus. Mauris tincidunt sem sed arcu. Fusce dui leo, imperdiet in, aliquam sit amet, feugiat eu, orci. Duis bibendum, lectus ut viverra rhoncus, dolor nunc faucibus libero, eget facilisis enim ipsum id lacus. Fusce dui leo, imperdiet in, aliquam sit amet, feugiat eu, orci.
</div>
</div>

Related

How to show/hide an element based on the presence of vertical scrollbars?

I want to show a div only if the page has scrollbars, and hide it if not. I want to do this in either pure CSS or JavaScript (if impossible in CSS).
I've found a question on Stack Exchange, but it's infested with that garbage jQuery cancer, so it's useless. I'm talking about pure JavaScript -- not jCancer.
Here's a pure JS solution, using this function:
const isScrollable = elem => elem.scrollHeight > elem.clientHeight;
Edit (description):
The function returns true if the element is scrollable, false otherwise.
Example:
const isScrollable = elem => elem.scrollHeight > elem.clientHeight;
// make scrollable divs have a red border
document.querySelectorAll("div").forEach(div => {
if (isScrollable(div)) div.style.borderColor = "red";
});
div {
border: 1px solid grey;
width: 200px;
overflow: auto;
margin-bottom: 1rem;
}
div#div1 {
height: 100px;
}
div#div2 {
height: 170px;
}
<div id="div1">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras maximus arcu quis mi eleifend tristique. Curabitur convallis tellus eget volutpat luctus. Fusce molestie molestie ante, vel fermentum erat. Fusce tempor erat eget dolor ultrices interdum. Pellentesque sed placerat nulla. Duis consequat, lorem quis vehicula lacinia, libero leo tincidunt odio, et porta ex turpis malesuada lorem. Proin sapien metus, facilisis sed urna non, vehicula commodo velit. Etiam venenatis laoreet neque vel sollicitudin. Suspendisse lacinia, lectus hendrerit dapibus laoreet, dui lorem condimentum enim, a vulputate ex ipsum ut nibh.
</div>
<div id="div2">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Cras maximus arcu quis mi eleifend tristique. Curabitur convallis tellus eget volutpat luctus. Fusce molestie molestie ante, vel fermentum erat.
</div>

How can i make my fixed header scroll away when a specific div hits it, or when it is 100px from the top

I can see lots of ways to do the opposite of what i am trying to achieve but noting for what I need.
I have a fixed header that is 100px tall. I want it to scroll away with the rest of the page when a specified div hits the header or it is 100px from the top of the screen.
I had was adding a scroll class to the header which was literally just making it position absolute, causing the header to jump of screen. I then translateY'd it back into view, this didn't work the same across all screen sizes.
My next idea is maybe keeping it fixed but adding a negative transformY to the header, dependent on scroll position. This would achieve the same effect I am going for but i'm not too sure how to achieve this.
If you need any more information then i am happy to provide it.
edit:
Here are some screen shots:
from the top of the page:
Then this is where i want the header to become un-fixed and scroll with the rest of the page:
Check out my solution. Hope this helps.
const headerEl = document.querySelector('header')
const targetEl = document.querySelector('#target')
const targetTopPos = targetEl.getBoundingClientRect().top
let isHeaderFixed = true
document.onscroll = () => {
const targetTopOffset = targetEl.getBoundingClientRect().top
if (isHeaderFixed && targetTopOffset < 100) {
headerEl.style.position = 'absolute'
headerEl.style.top = `${targetTopPos - 100}px`
isHeaderFixed = !isHeaderFixed
}
if (!isHeaderFixed && targetTopOffset >= 100) {
headerEl.style.position = 'fixed'
headerEl.style.top = '0px'
isHeaderFixed = !isHeaderFixed
}
}
body {
padding: 0;
margin: 0;
position: relative;
}
header {
position: fixed;
height: 100px;
width: 100%;
background: lightblue;
}
.content {
line-height: 100px;
}
.target {
width: 100%;
background: red;
}
<header>
Custom header
</header>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam suscipit tellus urna, ut tristique felis lobortis sed. Phasellus maximus at magna mattis vulputate. Pellentesque tempor, urna vitae congue pellentesque, est mauris faucibus nulla, vitae molestie leo purus a leo. Curabitur ut mi ac sem finibus consectetur a blandit massa. Morbi ornare tincidunt ipsum, et accumsan erat fringilla a. Cras egestas, nibh vel condimentum ultrices, nunc ipsum tempus magna, eu ullamcorper tortor magna id lacus. Morbi euismod lacus a ligula rutrum, in aliquet lectus blandit. Nam placerat sollicitudin lectus eu ornare. Etiam placerat diam eget magna blandit rutrum. Nulla et luctus massa. Sed sit amet mauris in magna tincidunt consequat. Proin mattis sit amet arcu a gravida. Nullam tempor urna nec dolor convallis consectetur sit amet a elit. Cras ut odio nec lacus efficitur porta nec sit amet justo.
</div>
<div id="target" class="target">target</div>
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam suscipit tellus urna, ut tristique felis lobortis sed. Phasellus maximus at magna mattis vulputate. Pellentesque tempor, urna vitae congue pellentesque, est mauris faucibus nulla, vitae molestie leo purus a leo. Curabitur ut mi ac sem finibus consectetur a blandit massa. Morbi ornare tincidunt ipsum, et accumsan erat fringilla a. Cras egestas, nibh vel condimentum ultrices, nunc ipsum tempus magna, eu ullamcorper tortor magna id lacus. Morbi euismod lacus a ligula rutrum, in aliquet lectus blandit. Nam placerat sollicitudin lectus eu ornare. Etiam placerat diam eget magna blandit rutrum. Nulla et luctus massa. Sed sit amet mauris in magna tincidunt consequat. Proin mattis sit amet arcu a gravida. Nullam tempor urna nec dolor convallis consectetur sit amet a elit. Cras ut odio nec lacus efficitur porta nec sit amet justo.
</div>
I should by default make .header {position: absolute} and add this class to css (not to element yet):
.header.active {
position: fixed;
top: 0;
left: 0;
width: 100%;
}
Then understand when we need to carry this event on header. JS will help:
var targetElement = document.querySelector( YOUR TARGET ELEMENT ),
header = document.querySelector('.header');
window.onscroll = function(event){
if ( targetElement.offsetTop > window.pageYOffset ) {
header.classList.add('active');
} else {
header.classList.remove('active');
}
}
Target element is element which when you want to reach it, header will be fixed.
If you need

Custom scrollbars thumb goes out of bounds

I am trying to create a thumb scroller that scrolls together with the default scroller (with animation). I wan finally able to implement it, be the only problem is, the custom scroller doesn't scroll at the exact position. If you scroll all the way down, the thumb scroller goes past its parent element.
Also, the thumb scroller is larger than the default scroller. Here's the math:
scrollBarThumb.style.height = (innerWrapper.parentElement.offsetHeight * innerWrapper.parentElement.offsetHeight / innerWrapper.scrollHeight) + 'px';
scrollBarPosition = clamp(scrollBarPosition, 0, scrolledToBottom)
scrollBarPosition = scrollBar.offsetHeight * scrollBarPosition / innerWrapper.scrollHeight;
The formulas I used are the accepted formulas for custom scrollers.
The two problems are: (they may be one issue, because I think if the height gets fixed, then the scrolling position will automatically get fixed as well.) First, the scrollers thumb is larger than the default. Second, the scrollers thumb goes past its parent when you scroll all the way down.
What am I doing wrong, and how can I fix it?
JSFiddle
console.clear();
var innerWrapper = document.getElementById('innerWrapper');
var scrollBar = document.getElementById('scrollbar');
var scrollBarThumb = scrollBar.firstElementChild
scrollBarThumb.style.height = (innerWrapper.parentElement.offsetHeight * innerWrapper.parentElement.offsetHeight / innerWrapper.scrollHeight) + 'px';
innerWrapper.addEventListener('mousewheel', handleScroll);
innerWrapper.addEventListener('DOMMouseScroll', handleScroll);
var duration = 35,
scrollSpeed = 2,
animateAmount = 30;
var scrolledToBottom = 0,
scrollDirection = 0, // 1 = scroll down, -1 = scroll up
animationID;
function handleScroll(e) {
// Cancel previous animation
cancelAnimationFrame(animationID);
// Scroll faster
scrollSpeed += 2;
// Reason for negative `-.wheelDelta` because Firefox
// return oposite value. See http://phrogz.net/js/wheeldelta.html
// Get 1 or -1
var delta = Math.max(-1, Math.min(1, (-e.wheelDelta || e.detail)));
// Check if scroll direction changed
if (scrollDirection != delta) {
scrollSpeed = 2; // Start slowly - restart speed
scrollDirection = delta;
}
var start = innerWrapper.parentElement.scrollTop,
end = start + animateAmount * scrollSpeed * delta, // Where to end the scroll
change = end - start, // base change in one scroll
step = 0, // current step in animation
tempScrollPosition; // Cannot assign any number yet (i.e. 0), because `scrollPosition` may be 0.
// Get amount of scrolled to bottom
scrolledToBottom = innerWrapper.scrollHeight - innerWrapper.parentElement.offsetHeight;
animationID = requestAnimationFrame(smoothScrollAnim); // Start animation
function smoothScrollAnim() {
animationID = requestAnimationFrame(smoothScrollAnim); // Restart animation
// Get scroll position
var scrollBarPosition = easeOut(step++, start, change, duration);
scrollBarPosition = clamp(scrollBarPosition, 0, scrolledToBottom)
scrollBarPosition = scrollBar.offsetHeight * scrollBarPosition / innerWrapper.scrollHeight;
// Apply scroll movement
scrollBarThumb.style.top = scrollBarPosition + 'px';
// Check if scroll finished (either animation finished, or bumped to top or bottom)
if (step >= duration || tempScrollPosition === scrollBarPosition) {
// Clean up
tempScrollPosition = null;
scrollSpeed = 2;
cancelAnimationFrame(animationID);
} else {
tempScrollPosition = scrollBarPosition;
}
}
}
function easeOut(time, begin, change, duration) {
time /= duration;
return -change * time * (time - 2) + begin;
}
function clamp(val, min, max) {
if (typeof min !== 'number') min = 0;
if (typeof max !== 'number') max = 1;
return Math.min(Math.max(val, min), max);
}
html {
height: 100%;
overflow-y: hidden;
}
body {
height: 100%;
overflow-y: hidden;
display: flex;
}
#outerWrapper {
height: 400px;
overflow: auto;
background-color: black;
}
#content {
background-image: url("http://images.freeimages.com/images/premium/previews/3037/30376024-beautiful-flower-portrait.jpg");
width: 400px;
}
#scrollbar {
height: 400px;
width: 50px;
background-color: orange;
border: 2px solid green;
}
#scrollbar_thumb {
background-color: yellow;
border: 2px solid blue;
position: relative;
}
<div id="outerWrapper">
<div id="innerWrapper">
<div id="content">
Lorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero
sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae. Lacinia dui cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus
Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae. Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus
enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar
justo neque dui ipsum vitae. Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames
ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae. Lacinia dui scelerisque
Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem
lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor Lorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie
vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum
vitae. Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque
Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae. Lacinia dui scelerisque Sed convallis nonummy orci
Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla.
Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae. Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet
consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet
risus Sed condimentum Cras. Nunc massa mauris tempor dolor pulvinar justo neque dui ipsum vitae. Lacinia dui scelerisque Sed convallis nonummy orci Vestibulum orci tempusLorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat
Ut tellus enim ante nulla molestie vitae sem interdum turpis. Fames ridiculus cursus pellentesque Vestibulum justo sem lorem neque accumsan nulla. Lacinia Suspendisse vitae libero sem et laoreet risus Sed condimentum Cras. Nunc massa mauris tempor
dolor
</div>
</div>
</div>
<div id="scrollbar">
<div id="scrollbar_thumb"></div>
</div>
For the scroll simply register the "scroll" event,
For the catching-delay effect use CSS3 transition
For the simple math involved see the example below:
const el = (sel, par) => (par || document).querySelector(sel);
const
elContent = el("#content"),
elHandler = el("#handler");
// FROM ELEMENT SCROLL TO HANDLER POSITION
const moveScrollbar = () => {
const
height = elContent.clientHeight,
scrollHeight = elContent.scrollHeight,
handlerHeight = height ** 2 / scrollHeight,
handlerTop = elContent.scrollTop / height * handlerHeight;
Object.assign(elHandler.style, {
height: `${handlerHeight}px`,
top: `${handlerTop}px`
});
}
moveScrollbar(); // At init
elContent.addEventListener("scroll", moveScrollbar); // and on scroll
* { margin: 0; box-sizing: border-box; }
#area {
display: flex;
}
#content {
height: 160px;
width: 300px;
font-size: 3rem;
background: #eee;
padding: 1rem;
}
#content {
overflow-y: scroll;
scrollbar-width: none;
-ms-overflow-style: none;
}
#content::-webkit-scrollbar {
width: 0;
height: 0;
}
#scrollbar {
flex: none;
position: relative;
background: #333;
width: 1rem;
}
#handler {
position: absolute;
top: 0;
background: orange;
width: 100%;
transition: 0.2s; /* smooth move */
}
<div id="area">
<div id="content">
Scroll and see the custom scrollbar move.<br>Lorem ipsum dolor sit amet consectetuer laoreet faucibus id ut et. Consequat Ut tellus enim ante nulla molestie vitae sem interdum turpis.
</div>
<div id="scrollbar">
<div id="handler"></div>
</div>
</div>
Then, to make the handler draggable, here's the formula:
// FROM HANDLER POSITION TO ELEMENT SCROLL:
const
height = elContent.clientHeight,
scrollHeight = elContent.scrollHeight,
scrollPos = scrollHeight / height * elHandler.clientTop;

Change height value from px to % in .dotdotdot script

How can I change the height value from 100 pixels to a percentage value? Lets say 50%. I'm fairly new to javascript...
<script language="javascript" type="text/javascript">
$(document).ready(function(){
$(".item-info-overlay p").dotdotdot({
ellipsis:"...",
wrap:"word",
height: 100,
after:"a.readmore",})
});
</script>
Rather than modifying the dotdotdot code, it might be simpler to calculate a pixel value based on your percentage and pass that pixel value to dotdotdot.
For example:
// define your desired percentage
var percentage = 50;
jQuery(function() {
// calculate pixel height based on your percentage
var dot_height = jQuery('div#container').height() * (percentage / 100);
jQuery("div#text").dotdotdot({
ellipsis: "...",
height: dot_height,
wrap: "word",
after: "a.readmore",
watch: "window"
});
});
div#container {
height: 150px;
background-color: #CCC;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jQuery.dotdotdot/1.7.2/jquery.dotdotdot.min.js"></script>
<div id="container">
<div id="text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Morbi commodo, ipsum sed pharetra gravida, orci magna rhoncus neque, id pulvinar odio lorem non turpis. Nullam sit amet enim. Suspendisse id velit vitae ligula volutpat condimentum. Aliquam erat
volutpat. Sed quis velit. Nulla facilisi. Nulla libero. Vivamus pharetra posuere sapien. Nam consectetuer. Sed aliquam, nunc eget euismod ullamcorper, lectus nunc ullamcorper orci, fermentum bibendum enim nibh eget ipsum. Donec porttitor ligula eu
dolor. Maecenas vitae nulla consequat libero cursus venenatis. Nam magna enim, accumsan eu, blandit sed, blandit a, eros. Quisque facilisis erat a dui. Nam malesuada ornare dolor.
Read More
</div>
</div>
If you're building a responsive site or your container is fluid, you can apply this same logic inside of a throttled resize handler.

Expanding a Read more / Read less jQuery script

I have this great script that uses jQuery to display a small portion of content & allow the user to read more/read less of the content.
Here is my current Fiddle: http://jsfiddle.net/Tqwdh/1/
Summary: When you click the image, it needs to reveal the additional text.
I would love to know how I can update this script to allow the user to click the associated image and it would display more of the text (as well as keeping the text link in place).
Can someone show me how I can achieve this?
Here is my example HTML:
<article id="post-5" >
<div class="more-less">
<div class="more-block">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed diam purus, lacinia eget placerat sit amet, bibendum nec nisl. Curabitur a mattis ipsum. Praesent quis nisi in purus malesuada rhoncus. Pellentesque ut quam eget libero congue lobortis. Nunc sed quam ac erat lobortis eleifend. Donec elementum sodales cursus. Aliquam porttitor massa nisi, in laoreet turpis. Sed consequat condimentum lorem ut dignissim. Sed hendrerit mauris ut massa fermentum laoreet. Pellentesque a leo vitae enim dictum lobortis. Praesent commodo feugiat velit iaculis malesuada.</p>
<p>Phasellus id elit ac lacus faucibus ullamcorper. Etiam ullamcorper pretium tellus, ut pharetra ante pulvinar vel. Sed neque diam, semper vel rhoncus non, congue ut sapien. Integer a mi eget libero elementum lobortis. Donec hendrerit egestas ligula sit amet eleifend. Curabitur pharetra venenatis tempor. Quisque pulvinar malesuada justo, ut euismod arcu pharetra vitae. Cras lobortis, ligula id euismod euismod, ipsum risus varius urna, faucibus gravida lectus mi nec nulla. Fusce eleifend fringilla nibh ut vulputate. Vivamus sagittis leo metus. Etiam facilisis convallis lacus adipiscing hendrerit. Duis ultricies euismod libero, nec blandit est semper a. Phasellus sit amet justo sed quam elementum lobortis. Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
<p>
<img src="http://placehold.it/300x187" alt="News Item 1" width="300" height="187" />
</p>
</article><!-- #post-## -->
and my jQuery:
$(function(){
// The height of the content block when it's not expanded
var adjustheight = 130;
// The "more" link text
var moreText = "Click to read more...";
// The "less" link text
var lessText = "Click to read less...";
// Sets the .more-block div to the specified height and hides any content that overflows
$(".more-less .more-block").css('height', adjustheight).css('overflow', 'hidden');
// The section added to the bottom of the "more-less" div
$(".more-less").append('<p style="display:block;margin-top:8px"></p>');
$("a.adjust").text(moreText);
$(".adjust").toggle(function() {
$(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
// Hide the [...] when expanded
$(this).parents("div:first").find("p.continued").css('display', 'none');
$(this).text(lessText);
}, function() {
$(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
$(this).parents("div:first").find("p.continued").css('display', 'block');
$(this).text(moreText);
});
});
Thank you :-)
You could just add a click handler to img like this:
DEMO
$(function(){
$('img').click(function(){
$(this).closest('article').find('.adjust').click();
});
});​
You will need to move the logic from the toggle handler to your own implementation, as you have more than one event source.
<article id="post-5" >
<div class="more-less">
<div class="more-block">…</div>
</div>
<p>
…
</p>
</article>
$(function(){
var adjustheight = 130; // The height of the content block when it's not expanded
var texts = {
more: "Click to read more…",
less: "Click to read less…"
};
$("article").each(function() {
var block = $(".more-block", this).css({height:adjustheight, overflow:'hidden'}),
cont = $("p.continue", this),
toggle = $('<a href="#'+this.id+'" class="adjust">').text(texts.more),
open = false;
$(".more-less", this).append($('<p style="display:block;margin-top:8px">').append(link));
$("a.adjust", this).click(function() {
open = !open;
block.css("height", open ? "auto" : adjustheight);
link.text(texts[open ? "less" : "more"]);
cont[open ? "show" : "hide"]();
}
});
});
Simply add the same behaviour of the "Click to read more" element to the image elements.
When you set the toggle handlers like this:
$(".adjust").toggle(function() {
$(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
// Hide the [...] when expanded
$(this).parents("div:first").find("p.continued").css('display', 'none');
$(this).text(lessText);
}, function() {
$(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
$(this).parents("div:first").find("p.continued").css('display', 'block');
$(this).text(moreText);
});
Just use jQuery's multiple selector to select the image elements also, like in this example:
$(".adjust, #img1, #img2").toggle(function() {
$(this).parents("div:first").find(".more-block").css('height', 'auto').css('overflow', 'visible');
// Hide the [...] when expanded
$(this).parents("div:first").find("p.continued").css('display', 'none');
$(this).text(lessText);
}, function() {
$(this).parents("div:first").find(".more-block").css('height', adjustheight).css('overflow', 'hidden');
$(this).parents("div:first").find("p.continued").css('display', 'block');
$(this).text(moreText);
});
Demo
Hope it helps.
var maxLength = 50;
$('.N_DESC').each( function (e) {
const thisVal = $(this).text();
const thisLength = $.trim(thisVal).length;
const noticeStr = thisVal.substring(0, maxLength);
const removedStr = thisVal.substring(maxLength, thisLength);
if(thisLength > maxLength){
$(this).empty().html(noticeStr);
$(this).append('<span class="more-text">'+ removedStr +'</span>');
$(this).append(`Read More..`);
}
});
$(document).on('click', '.read-more', function (e) {
$(this).closest('span').find('.more-text').show();
$(this).addClass('read-less');
$(this).removeClass('read-more');
$(this).html('Read Less..');
});
$(document).on('click', '.read-less', function (e) {
$(this).closest('span').find('.more-text').hide();
$(this).addClass('read-more');
$(this).removeClass('read-less');
$(this).html('Read More..');
});
.N_DESC .more-text{
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span class="N_DESC">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim. Fusce est. Vivamus a tellus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Proin pharetra nonummy pede. Mauris et orci. Aenean nec lorem. In porttitor.</span>
<br>
<span class="N_DESC">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero, sit amet commodo magna eros quis urna. Nunc viverra imperdiet enim.</span>
<br>
<span class="N_DESC">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas porttitor congue massa. Fusce posuere, magna sed pulvinar ultricies, purus lectus malesuada libero</span>

Categories

Resources