I have a read more read less function with html and js, function is working fine with one paragraph when I use again for another paragraph then second function not working, I would like to multiple use in same page, please check
function myFunction() {
var dots = document.getElementById("dots");
var moreText = document.getElementById("more");
var btnText = document.getElementById("myBtn");
if (dots.style.display === "none") {
dots.style.display = "inline";
btnText.innerHTML = "READ MORE";
moreText.style.display = "none";
} else {
dots.style.display = "none";
btnText.innerHTML = "READ LESS";
moreText.style.display = "inline";
}
}
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<span id="dots">...</span><span id="more"> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</span></p>
<div class="col-md-12">
<button onclick="myFunction()" id="myBtn" class="rm">READ MORE</button>
</div>
You can try to find out various element with relation to button which was clicked. You can also use class name instead of Id to select elements.
function myFunction(event) {
const parentSibling = event.target.parentElement.previousElementSibling;
const dots = parentSibling.querySelector(".dots");
const moreElement = parentSibling.querySelector(".more");
const btnElement = event.target;
if (dots.style.display === "none") {
dots.style.display = "inline";
btnElement.innerHTML = "READ MORE";
moreElement.style.display = "none";
} else {
dots.style.display = "none";
btnElement.innerHTML = "READ LESS";
moreElement.style.display = "inline";
}
}
<p>1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<span class="dots">...</span><span class="more" style="display: none"> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</span></p>
<div class="col-md-12">
<button onclick="myFunction(event)" class="myBtn" class="rm">READ MORE</button>
</div>
<p>2. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<span class="dots">...</span><span class="more" style="display: none"> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</span></p>
<div class="col-md-12">
<button onclick="myFunction(event)" class="myBtn" class="rm">READ MORE</button>
</div>
You can also use a single handler in the parent, which will execute the logic based on the clicked element myBtn.
function myFunction(event) {
event.preventDefault();
if(!event.target.classList.contains('myBtn')) {
return;
}
const parentSibling = event.target.parentElement.previousElementSibling;
const dots = parentSibling.querySelector(".dots");
const moreElement = parentSibling.querySelector(".more");
const btnElement = event.target;
if (dots.style.display === "none") {
dots.style.display = "inline";
btnElement.innerHTML = "READ MORE";
moreElement.style.display = "none";
} else {
dots.style.display = "none";
btnElement.innerHTML = "READ LESS";
moreElement.style.display = "inline";
}
}
<div onclick="myFunction(event)">
<p>1. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<span class="dots">...</span><span class="more" style="display: none"> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</span></p>
<div class="col-md-12">
<button class="myBtn" class="rm">READ MORE</button>
</div>
<p>2. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.<span class="dots">...</span><span class="more" style="display: none"> Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</span></p>
<div class="col-md-12">
<button class="myBtn" class="rm">READ MORE</button>
</div>
</div>
You can add read more read less functionality with pure JavaScript using only 10 lines code. More details here https://developer.wikimint.com/2022/07/read-more-read-less-using-javascript.html
<script type="text/javascript">
var show = document.querySelectorAll('[role="show"]');
for (var i = 0; i < show.length; i++) {
show[i].addEventListener("click", function() {
this.nextElementSibling.style.display = 'contents';
this.style.display = 'none';
});
}
var hide = document.querySelectorAll('[role="hide"]');
for (var i = 0; i < hide.length; i++) {
hide[i].addEventListener("click", function() {
this.parentElement.style.display = 'none';
this.parentElement.previousElementSibling.style.display = 'contents';
});
}
</script>
Using the above JavaScript, you can add read more read less functionality to any number of elements.
No need to add onClick attributes or id attributes.
You can do this without javascript all together, just by using a checkbox and the sibling selector (~).
section .section-toggler,
section .more {
display: none;
}
section .section-toggler:checked ~ p > .more {
display: inline;
}
section .section-toggler:checked ~ p > .dots {
display: none;
}
section > label {
cursor: pointer;
color: #71acbf;
}
<section>
<input class="section-toggler" id="section-1" type="checkbox" />
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
<span class="dots">...</span>
<span class="more">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."</span>
</p>
<label for="section-1">Read more...</label>
</section>
Related
I created two content fields. In this area, I am trying to scroll the left content up and the right content down with the mouse wheel. I couldn't make it independent from page scroll. When the general page (behind page) scroll is finished, scrolling stops for aaa and bbb. can i do this any other way
$(document).ready(function(){
let screenHeighter = $(window).innerHeight();
let scrollReset = $(window).scrollTop();
let scLeftHeight = $(".bbb")[0].scrollHeight;
let scRightHeight = $(".ccc")[0].scrollHeight;
let scrollElement = $(".ccc-scroller");
let scrollElementX = $(".bbb-scroller");
let defLeftTop = ((scLeftHeight - screenHeighter) / 2) + 100;
let defRightTop = ((scRightHeight - screenHeighter) / 2) - 100;
scrollElement.css({"transform": "translate3d(0px, -" + defRightTop + "px, 0px)"});
scrollElementX.css({"transform": "translate3d(0px, -" + defLeftTop + "px, 0px)"});
$('.aaa').on('mousewheel', function(e){
let logger = console.log();
$(window).scroll(function () {
let scroll = $(window).scrollTop();
let scrollX = scrollReset;
let scrollPos = (scroll - scrollX) - defRightTop;
let scrollPosX = ((scroll - scrollX) + defLeftTop) * -1;
if (scrollPos < 0 && (scrollPos * -1) < (scRightHeight - screenHeighter)) {
scrollElement.css({"transform": "translate3d(0px, " + scrollPos + "px, 0px)"});
}
if (scrollPosX < 0 && (scrollPosX * -1) < (scRightHeight - screenHeighter)) {
scrollElementX.css({"transform": "translate3d(0px, " + scrollPosX + "px, 0px)"});
}
});
});
})
.aaa {
position:fixed;
top:0;
height:100%;
width:100%;
background:#222;
color:#fff;
}
.bbb {
position:absolute;
top:0;
left:0;
width:50%;
height:100%;
border-right:1px solid rgba(255,255,2550.1);
}
.ccc {
position:absolute;
top:0;
height:100%;
right:0;
width:50%;
border-right:1px solid rgba(255,255,2550.1);
}
.ccc-scroller {
position:relative;
overflow:hidden;
}
.bbb-scroller {
position:relative;
overflow:hidden;
}
.package {
padding:50px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="aaa">
<div class="bbb">
<div class="bbb-scroller">
<div class="package">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<div class="package">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<div class="package">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
</div>
<div class="ccc">
<div class="ccc-scroller">
<div class="package">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<div class="package">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<div class="package">
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
</div>
</div>
</div>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
I am getting paragraph content from the database. I am trying to show 300 characters on screen adding the read more which is working.
My issue is, I have to display the less also when user click on read more so that the user can less the content. I tried below code
$(document).ready(function() {
var maxLength = 300;
$(".countParawords").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() {
$('.less').show();
$(this).append(' LESS');
$(this).siblings(".more-text").contents().unwrap();
$(this).remove();
});
$(".less").click(function() {
$(this).siblings(".more-text").contents().wrap();
$(this).remove();
});
});
.box {
width: 500px;
margin: auto;
}
.box .more-text {
display: none;
}
.box .less {
display: none;
}
<div class="box">
<p class="countParawords">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
Modified your code to get it working, there are few changes, will explain in between the code itself.
$(document).ready(function() {
var maxLength = 300;
var readMore = null;
$(".countParawords").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>');
// Stored the content inside an global variable as on unwrapping the element, the element is removed from the DOM.
readMore = $(this).find(".more-text").contents();
}
});
$(".read-more").click(function() {
// Added parent method to target parent element as this element will be hidden so content inside it won't be visible
$(this).parent().append(' LESS');
$(this).siblings(".more-text").contents().unwrap();
$('.less').show();
$(this).hide();
// Added click listener inside the read more click listener as element would only be created after clicking on read more
var parentThis = this;
// Stored parent "this ref" in a variable to remove the less element
$(".less").click(function() {
// Wrapped the previously stored content in span as earlier.
readMore.wrap('<span class="more-text"></span>');
// Made read more visible
$(parentThis).show();
// Removed the less element
$(this).remove();
});
});
});
.box {
width: 500px;
margin: auto;
}
.box .more-text {
display: none;
}
.box .less {
display: none;
}
<div class="box">
<p class="countParawords">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
Do read the comment through out the code
I have made few changes to your js code to make it work, please try this:
$(document).ready(function() {
var maxLength = 300;
var moretxt = "...Read More";
var lesstxt = "...Read Less";
$(".countParawords").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('<span class="more-text">' + removedStr + '</span>');
$(this).append(' ' + moretxt + '');
}
});
$(".read-more").click(function() {
if($(this).hasClass("more")){
$(this).removeClass("more");
$(this).text(lesstxt);
$(this).siblings(".more-text").show();
}
else {
$(this).addClass("more");
$(this).text(moretxt);
$(this).siblings(".more-text").hide();
}
});
});
.box {
width: 500px;
margin: auto;
}
.box .more-text {
display: none;
}
.box .less {
display: none;
}
<div class="box">
<p class="countParawords">Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure
dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. Lorem ipsum dolor sit amet, consectetur adipisicing
elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit essecillum
dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
Hope it helps.
I'm working on a website with some kind of a JavaScript "input" tabs. Let say user type "running" in input and press submit than application display some quote about running, but when user type something that is not exist in predefined dataset (data-name) than application display generic content.
Everything is working except generic content(class="generic").
How can I add generic content when input value is not existing in dataset values in the app section.
You can try in this fiddle: http://jsfiddle.net/e10nLbg2/1/
Here is my code:
.data, .generic {
visibility: hidden;
opacity: 0;
background: blue;
padding: 50px;
color: white;
transition: opacity 1s ease;
position: absolute;
}
.active {
visibility: visible;
opacity: 1;
}
<input type="text" class="input">
<input type="submit" class="submit" value="SUBMIT">
<section class="app">
<div class="data" data-name="running">RUNNING - Lorem ipsum dolor sit...
</div>
<div class="data" data-name="walking">WALKING - Lorem ipsum dolor
sit...
</div>
<div class="generic">GENERIC - Lorem ipsum dolor sit...
</div>
</section>
var submit = document.querySelector('.submit');
submit.onclick = function(){
var input = document.querySelector('.input').value;
var e = input.toLowerCase();
var element = document.querySelector('[data-name="'+ e +'"]');
var generic = document.querySelector('.generic');
var active = document.querySelector('.active');
if(active){
active.classList.remove('active');
//generic.classList.add('active');
}else{
//generic.classList.remove('active');
}
element.classList.add('active');
}
On submit event you need to remove .active from active element and generic one as well, then set active the one that fits user input, else - set active generic:
var submit = document.querySelector('.submit');
submit.onclick = function() {
let e = document.querySelector('.input').value.toLowerCase();
let element = document.querySelector('[data-name="'+ e +'"]');
let generic = document.querySelector('.generic');
let active = document.querySelector('.active');
if (active) active.classList.remove('active');
generic.classList.remove('active');
if (element)
element.classList.add('active');
else
generic.classList.add('active');
}
.data, .generic {
visibility: hidden;
opacity: 0;
background: blue;
padding: 50px;
color: white;
transition: opacity 1s ease;
position: absolute;
}
.active {
visibility: visible;
opacity: 1;
}
input {
height: 30px;
border-radius: 5px;
box-sizing: border-box;
outline: none;
}
input[type="text"] {
background: #e6e6e6;
color: grey;
outline: none;
padding: 15px;
border: 0;
}
<input type="text" class="input">
<input type="submit" class="submit" value="SUBMIT">
<div class="data" data-name="running">RUNNING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<div class="data" data-name="playing">PLAYING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<div class="data" data-name="dancing">DANCING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<div class="data" data-name="walking">WALKING - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
<div class="generic">GENERIC - Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
I have fixed div with menu. There are also some sections. Each section has data attribute set to specific class name (eg. data-menu="black").
What I'd like to achieve is when user scroll and a section with this attribute is under a fixed div, this div gets the class based on data-menu attribute. And remove when section isn't below anymore.
This is my is fiddle: https://jsfiddle.net/pt3taagp/1/
HTML
<div class="fixed-menu">
<ul>
<li>menu 1</li>
<li>menu 2</li>
<li>menu 3</li>
<li>etc.</li>
</ul>
</div>
<section data-menu="menu-black">
<img src="http://placehold.it/600x600/ffffff/000000">
</section>
<section data-menu="menu-white">
<img src="http://placehold.it/600x600/000000/ffffff">
</section>
<div>some other content</div>
CSS
fixed-menu {
position:fixed;
top:50px;
left:50px;
width:250px;
background-color:red
}
.fixed-menu.menu-black {
background-color:#000;
}
.fixed-menu.menu-white {
background-color:#FFF;
}
By default menu has red background but when section with data-menu attribute=menu-white is under I'd like this menu to change background color to white, etc.
JQuery offet() method gives relative positioning of a particular element. Check out this fiddle.
Although, this will only work if you have fixed section height.
window.onscroll = function() {
myFunction()
};
function myFunction() {
var x = $("#mainmenu").offset();
if (x.top < 612) {
document.getElementById("mainmenu").className = "fixed-menu menu-white";
} else if (x.top > 612) {
document.getElementById("mainmenu").className = "fixed-menu menu-black";
}else{
document.getElementById("mainmenu").className = "fixed-menu";
}
}
.fixed-menu {
position: fixed;
top: 50px;
left: 50px;
width: 250px;
background-color: red
}
.menu-black {
background-color: #000;
color: white;
}
.menu-white {
background-color: #FFF;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="main">
<div id="mainmenu" class="fixed-menu">
<ul>
<li>menu 1</li>
<li>menu 2</li>
<li>menu 3</li>
<li>etc.</li>
</ul>
</div>
<div class="black">
<section data-menu="menu-black">
<img src="http://placehold.it/600x600/ffffff/000000">
</section>
</div>
<div id="white">
<section data-menu="menu-white">
<img src="http://placehold.it/600x600/000000/ffffff">
</section>
</div>
<div class="some-other-content">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
</div>
</div>
Thanks to how get current mouse position on scroll and select all elements present at specified position the solution is:
get the mouse position in any case
handle the window scroll event
while scrolling, if the element under current mouse position is a section: change class according to the data-menu. In all other cases remove the added class.
var xMousePos = 0;
var yMousePos = 0;
var lastScrolledLeft = 0;
var lastScrolledTop = 0;
function GetSectionElementsAt(x, y) {
var elements = $('section').map(function() {
var thisObj = $(this);
var offset = thisObj.offset();
var l = offset.left;
var t = offset.top;
var h = thisObj.height();
var w = thisObj.width();
var maxx = l + w;
var maxy = t + h;
return (y <= maxy && y >= t) && (x <= maxx && x >= l) ? thisObj : null;
});
return elements;
}
$(document).mousemove(function(e) {
xMousePos = e.pageX;
yMousePos = e.pageY;
});
$(window).on('scroll', function (e) {
if(lastScrolledLeft != $(document).scrollLeft()){
xMousePos -= lastScrolledLeft;
lastScrolledLeft = $(document).scrollLeft();
xMousePos += lastScrolledLeft;
}
if(lastScrolledTop != $(document).scrollTop()){
yMousePos -= lastScrolledTop;
lastScrolledTop = $(document).scrollTop();
yMousePos += lastScrolledTop;
}
var eleAtCurrentMousePos = GetSectionElementsAt(xMousePos, yMousePos);
if (eleAtCurrentMousePos.length > 0) {
var classToSet = eleAtCurrentMousePos[0].data('menu');
if (!$('div.fixed-menu').hasClass(classToSet)) {
$('div.fixed-menu').removeClass('menu-white menu-black').addClass(classToSet);
}
} else {
$('div.fixed-menu').removeClass('menu-white menu-black');
}
});
.fixed-menu {
position: fixed;
top: 50px;
left: 50px;
width: 250px;
background-color: red
}
.fixed-menu.menu-black {
background-color: #000;
}
.fixed-menu.menu-white {
background-color: #FFF;
}
<script src="https://code.jquery.com/jquery-1.12.3.min.js"></script>
<div class="fixed-menu">
<ul>
<li>menu 1</li>
<li>menu 2</li>
<li>menu 3</li>
<li>etc.</li>
</ul>
</div>
<section data-menu="menu-black">
<img src="http://placehold.it/600x600/ffffff/000000">
</section>
<section data-menu="menu-white">
<img src="http://placehold.it/600x600/000000/ffffff">
</section>
<div class="some-other-content">
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore
magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla
pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est
laborum.
</p>
</div>
I have implemented this using jquery but want to create a component in react to do the same
<script>
jQuery(document).ready(function() {
var offset = 220;
var duration = 500;
jQuery(window).scroll(function() {
if (jQuery(this).scrollTop() > offset) {
jQuery('.move-top').fadeIn(duration);
} else {
jQuery('.move-top').fadeOut(duration);
}
});
jQuery('.move-top').click(function(event) {
event.preventDefault();
jQuery('html, body').animate({scrollTop: 0}, duration);
return false;
})
});
</script>
In my page footer
↑
First, we need to track the page as it's scrolled in the state of the component. This tracking should only be happening while the component is mounted. This can be done like so:
getInitialState: function() {
return { scrollTop: 0 };
},
componentWillMount: function() {
window.addEventListener('scroll', this.handleScroll);
},
componentWillUnmount: function() {
window.removeEventListener('scroll', this.handleScroll);
},
handleScroll: function() {
this.setState({scrollTop: $(window).scrollTop()});
},
Note: this is still using jQuery to get the current scroll position. See this question for doing this without jQuery.
Then we need to render the component:
scrollToTop: function() {
$(window).animate({scrollTop: 0}, this.props.duration);
},
render: function() {
if (this.state.scrollTop < this.props.offset) {
return null;
}
return <a href="#" className="move-top" onClick={this.scrollToTop}>↑</a>
}
This is still using jQuery to do the actual scrolling. Have a look a this question for scrolling without jQuery.
If you want this component to fade in and out, you should wrap it in a ReactCSSTransitionGroup and use CSS animations. This is documented on the React docs.
Here's a JSFiddle demo.
If you'd like to avoid jQuery altogether
var Example = React.createClass({
scrollUp: function () {
var doc = document.documentElement;
var top = (window.pageYOffset || doc.scrollTop) - (doc.clientTop || 0);
if (top > 0) {
window.scrollTo(0, top - 15)
setTimeout(this.scrollUp, 10)
}
},
render: function () {
return (<div><h1>Page Header</h1>
<div ref="container" className="container">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore
et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut
aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint
occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<a className="move-top" onClick={this.scrollUp}>Up</a>
</div>
</div>);
}
});
After searching on google, I reached a jQuery code as your needs in JSFiddle . Then, I reordered your jQuery:
$(document).ready(function() {
$(window).scroll(function() {
if ($(this).scrollTop() > 100) {
$('.move-top').fadeIn();
} else {
$('.move-top').fadeOut();
}
});
$('.move-top').click(function() {
$("html, body").animate({
scrollTop: 0
}, 600);
return false;
});
});
.container {
min-height: 1000px;
}
.move-top {
position: fixed;
bottom: 50px;
right: 100px;
display: none;
padding: 10px 15px;
color: #fff;
font-weight: 600;
background: #333;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.2/jquery.min.js"></script>
<h1>Page Header</h1>
<div class="container">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor
in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</p>
<a class="move-top" href="#">↑</a>
</div>
<h3>Page Footer</h3>
Use the following code like this :
smoothScroll.scrollTo(ID_OF_DOM_ELEMENT, OPTIONAL_CALLBACK_ON_SCROLL_DONE)
Code :
var smoothScroll = {
timer: null,
stop: function () {
clearTimeout(this.timer);
},
scrollTo: function (id, callback) {
var settings = {
duration: 1000,
easing: {
outQuint: function (x, t, b, c, d) {
return c*((t=t/d-1)*t*t*t*t + 1) + b;
}
}
};
var percentage;
var startTime;
var node = document.getElementById(id);
var nodeTop = node.offsetTop;
var nodeHeight = node.offsetHeight;
var body = document.body;
var html = document.documentElement;
var height = Math.max(
body.scrollHeight,
body.offsetHeight,
html.clientHeight,
html.scrollHeight,
html.offsetHeight
);
var windowHeight = window.innerHeight
var offset = window.pageYOffset;
var delta = nodeTop - offset;
var bottomScrollableY = height - windowHeight;
var targetY = (bottomScrollableY < delta) ?
bottomScrollableY - (height - nodeTop - nodeHeight + offset):
delta;
startTime = Date.now();
percentage = 0;
if (this.timer) {
clearInterval(this.timer);
}
function step () {
var yScroll;
var elapsed = Date.now() - startTime;
if (elapsed > settings.duration) {
clearTimeout(this.timer);
}
percentage = elapsed / settings.duration;
if (percentage > 1) {
clearTimeout(this.timer);
if (callback) {
callback();
}
} else {
yScroll = settings.easing.outQuint(0, elapsed, offset, targetY, settings.duration);
window.scrollTo(0, yScroll);
this.timer = setTimeout(step, 10);
}
}
this.timer = setTimeout(step, 10);
}
};
I think react-scroll is worth being mentioned, add this to your component's click handler (onClick={this.handleClick})
import Scroll from 'react-scroll'
...
Scroll.animateScroll.scrollToTop({options})
...
With options being an object specified as per Props/Options
I don't recommend mixing jQuery and React/Angular. It can be done easily using 'react-scroll' like this:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { animateScroll as scroll } from 'react-scroll';
class Scrolltotop extends Component {
ScrollTo() {
scroll.scrollToTop();
}
render() {
return (
<div className="move-top-wrap">
<div onClick={this.ScrollTo} class="move-top">↑</div>
</div>
);
}
}
export default Scrolltotop;
You can check out all basic examples of react-scroll usage here.
You can now import and use this component anywhere.