Accordion JS hyperlink propagation - javascript

I am working on a website with multiple accordions on each page with download links. I found a beautiful accordion by Ahmet Aksungur, but the hyperlinks don’t work with his code. I’ve tried adding preventDefault() and stopPropagation() -- $.on('click', 'a', function (e) { e.stopPropegation();}) -- – this work great (once!) – but the problem is that after the initial download, none of the accordions or download links work.
Could anyone suggest a way to stopPropagation on an event and allow normal function of the rest of the accordions. Thanks.
codepen: https://codepen.io/doncroy/pen/abZBZyL
'''
<script>
(function () {
"use strict";
var jQueryPlugin = (window.jQueryPlugin = function (ident, func) {
return function (arg) {
if (this.length > 1) {
this.each(function () {
var $this = $(this);
if (!$this.data(ident)) {
$this.data(ident, func($this, arg));
}
});
return this;
} else if (this.length === 1) {
if (!this.data(ident)) {
this.data(ident, func(this, arg));
}
return this.data(ident);
}
};
});
})();
(function () {
"use strict";
function Accordion($roots) {
var element = $roots;
var accordion = $roots.first("[data-accordion]");
var accordion_target = $roots.find("[data-accordion-item]");
var accordion_content = $roots.find("[data-accordion-content]");
$(accordion_target).click(function () {
$(this).toggleClass("opened");
$(this).find(accordion_content).slideToggle("slow");
$(this).siblings().find(accordion_content).slideUp("slow");
$(this).siblings().removeClass("opened");
});
}
$.fn.Accordion = jQueryPlugin("Accordion", Accordion);
$("[data-accordion]").Accordion();
function Ripple_Button($root) {
var elements = $root;
var ripple_btn = $root.first("[data-ripple]");
$(ripple_btn).on("click", function (event) {
event.preventDefault();
var $div = $("<div/>"),
btnOffset = ripple_btn.offset(),
xPos = event.pageX - btnOffset.left,
yPos = event.pageY - btnOffset.top;
$div.addClass("ripple-effect");
$div.css({
height: ripple_btn.height(),
width: ripple_btn.height(),
top: yPos - $div.height() / 2,
left: xPos - $div.width() / 2,
background: ripple_btn.data("ripple") || "#ffffff26"
});
ripple_btn.append($div);
window.setTimeout(function () {
$div.remove();
}, 2000);
});
}
$.fn.Ripple_Button = jQueryPlugin("Ripple_Button", Ripple_Button);
$("[data-ripple]").Ripple_Button();
})();
</script>
'''
'''
<div class="container">
<div class="aks-accordion" itemscope itemtype="https://schema.org/FAQPage" data-accordion="">
<div class="aks-accordion-row">
<div class="aks-accordion-item" itemscope itemprop="mainEntity" itemtype="https://schema.org/Question" data-accordion-item="" data-ripple="#2c612c26">
<div class="aks-accordion-item-row">
<div class="aks-accordion-item-icon">
<svg class="aks-accordion-item-icon-open" viewBox="0 0 512 512">
<path d="M492,236H276V20c0-11.046-8.954-20-20-20c-11.046,0-20,8.954-20,20v216H20c-11.046,0-20,8.954-20,20s8.954,20,20,20h216
v216c0,11.046,8.954,20,20,20s20-8.954,20-20V276h216c11.046,0,20-8.954,20-20C512,244.954,503.046,236,492,236z" />
</svg>
<svg class="aks-accordion-item-icon-close" viewBox="0 0 512 512">
<path d="M492,236H20c-11.046,0-20,8.954-20,20c0,11.046,8.954,20,20,20h472c11.046,0,20-8.954,20-20S503.046,236,492,236z" />
</svg>
</div>
<div class="aks-accordion-item-title">
<h4 itemprop="name">Dropdown Title</h4>
</div>
</div>
<div class="aks-accordion-item-content" itemscope itemprop="acceptedAnswer" itemtype="https://schema.org/Answer" data-accordion-content="">
<li><div id="#" onclick='recordVisit(this.id, "link")'><i class="fas fa-file-download"></i>PLACEHOLDER</div></li>
<li><div id="#" onclick='recordVisit(this.id, "link")'><i class="fas fa-file-download"></i>PLACEHOLDER</div></li>
<li><div id="#" onclick='recordVisit(this.id, "link")'><i class="fas fa-file-download"></i>PLACEHOLDER</div></li>
</div>
</div>
</div>
</div>
</div>
'''

I found the answer. The problem with the stopPropagation() written into the JS was that it affected the accordions globally. The solution was to use an inline onclick event on each of the links.
<li><div id="#" onclick='recordVisit(this.id, "link"); event.stopPropagation();'><i class="fas fa-file-download"></i>PLACEHOLDER</div></li>

Related

How do I hide the menu when I click outside?

There is a website, there is a mobile version. The mobile version has a drop-down menu. This menu works fine, but it doesn't close when clicked outside the block.
I've been looking for a solution on the Internet for a really long time, but nothing came up( I'll be very grateful for the help!
HTML
<header class="header" id="header">
<div class="container">
<div class="header__inner" id="header">
<div class="header__logo">
<img src="Images/ActiveBox_logo.png" alt="Logo" class="img__logo">
</div>
<nav class="nav" id="nav">
Features
Works
Our Team
Testimonials
Download
</nav>
<button class="burger" type="button" id="navToggle">
<span class="burger__item">Menu</span>
</button>
</div> <!-- header__inner -->
</div>
</header>
JS
let header = $("#header");
let intro = $("#intro");
let introH = intro.innerHeight();
let scrollPos = $(window).scrollTop();
let nav = $("#nav");
let navToggle = $("#navToggle");
checkScroll(scrollPos, introH);
$(window).on("scroll resize", function() {
introH = intro.innerHeight();
scrollPos = $(this).scrollTop();
checkScroll(scrollPos, introH);
});
function checkScroll(scrollPos, introH) {
if( scrollPos > introH ) {
header.addClass("fixed");
} else {
header.removeClass("fixed");
}
}
/* Smooth scroll */
$("[data-scroll]").on("click", function(event) {
event.preventDefault();
let elementId = $(this).data('scroll');
let elementOffset = $(elementId).offset().top;
nav.removeClass("show");
$("html, body").animate({
scrollTop: elementOffset - 70
}, 700);
});
// Nav Toggle
navToggle.on("click", function(event) {
event.preventDefault();
nav.toggleClass("show");
});
How about something like this?
$(document).on('click', function (e) {
if ($(e.target).closest("#box").length === 0) {
$("#box").hide();
console.log('clicked outside the box');
}
else {
console.log('clicked on the box');
}
});
#box{
width:100px;
height:40px;
background-color:blue;
color:white;
padding:5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id='box'>
click me, then click outside
</div>

JS slider has one too many slides. Can't figure out why

I have a slider which is supposed to show only three slides, but it continues (both automatically or by click) to a fourth blank slide. I don't see where the number of slides is set in the code. Would really appreciate some educated eyes on this.
The JS
$(document).ready(function() {
var $slider = $(".slider"),
$slideBGs = $(".slide__bg"),
diff = 0,
curSlide = 0,
numOfSlides = $(".slide").length-1,
animating = false,
animTime = 500,
autoSlideTimeout,
autoSlideDelay = 6000,
$pagination = $(".slider-pagi");
function createBullets() {
for (var i = 0; i < numOfSlides+1; i++) {
var $li = $("<li class='slider-pagi__elem'></li>");
$li.addClass("slider-pagi__elem-"+i).data("page", i);
if (!i) $li.addClass("active");
$pagination.append($li);
}
};
createBullets();
function manageControls() {
$(".slider-control").removeClass("inactive");
if (!curSlide) $(".slider-control.left").addClass("inactive");
if (curSlide === numOfSlides) $(".slider-control.right").addClass("inactive");
};
function autoSlide() {
autoSlideTimeout = setTimeout(function() {
curSlide++;
if (curSlide > numOfSlides) curSlide = 0;
changeSlides();
}, autoSlideDelay);
};
autoSlide();
function changeSlides(instant) {
if (!instant) {
animating = true;
manageControls();
$slider.addClass("animating");
$slider.css("top");
$(".slide").removeClass("active");
$(".slide-"+curSlide).addClass("active");
setTimeout(function() {
$slider.removeClass("animating");
animating = false;
}, animTime);
}
window.clearTimeout(autoSlideTimeout);
$(".slider-pagi__elem").removeClass("active");
$(".slider-pagi__elem-"+curSlide).addClass("active");
$slider.css("transform", "translate3d("+ -curSlide*100 +"%,0,0)");
$slideBGs.css("transform", "translate3d("+ curSlide*50 +"%,0,0)");
diff = 0;
autoSlide();
}
function navigateLeft() {
if (animating) return;
if (curSlide > 0) curSlide--;
changeSlides();
}
function navigateRight() {
if (animating) return;
if (curSlide < numOfSlides) curSlide++;
changeSlides();
}
$(document).on("mousedown touchstart", ".slider", function(e) {
if (animating) return;
window.clearTimeout(autoSlideTimeout);
var startX = e.pageX || e.originalEvent.touches[0].pageX,
winW = $(window).width();
diff = 0;
$(document).on("mousemove touchmove", function(e) {
var x = e.pageX || e.originalEvent.touches[0].pageX;
diff = (startX - x) / winW * 70;
if ((!curSlide && diff < 0) || (curSlide === numOfSlides && diff > 0)) diff /= 2;
$slider.css("transform", "translate3d("+ (-curSlide*100 - diff) +"%,0,0)");
$slideBGs.css("transform", "translate3d("+ (curSlide*50 + diff/2) +"%,0,0)");
});
});
$(document).on("mouseup touchend", function(e) {
$(document).off("mousemove touchmove");
if (animating) return;
if (!diff) {
changeSlides(true);
return;
}
if (diff > -6 && diff < 6) {
changeSlides();
return;
}
if (diff <= -6) {
navigateLeft();
}
if (diff >= 6) {
navigateRight();
}
});
$(document).on("click", ".slider-control", function() {
if ($(this).hasClass("left")) {
navigateLeft();
} else {
navigateRight();
}
});
$(document).on("click", ".slider-pagi__elem", function() {
curSlide = $(this).data("page");
changeSlides();
});
});
The HTML
<div class="slider-container">
<div class="slider-control left inactive"></div>
<div class="slider-control right"></div>
<ul class="slider-pagi"></ul>
<div class="slider">
<div class="slide slide-0 active">
<div class="slide__bg"></div>
<div class="slide__content">
<!--<svg class="slide__overlay" viewBox="0 0 720 405" preserveAspectRatio="xMaxYMax slice">
<path class="slide__overlay-path" d="M0,0 150,0 500,405 0,405" />
</svg>-->
<div class="slide__text">
<h2 class="slide__text-heading"><b>New</b> featured products</h2>
<h3 class="slide__text-sub-head">Ives<sup>®</sup> hands-free door pulls</h3>
<p class="slide__text-desc">Ives offers hands-free pulls and door opening tools that enable pedestrians to operate the door with an arm or foot to avoid contacting surfaces with their hands. This is a cost-effective solution for retrofitting high-traffic mechanical applications to hands-free.<br><a class="slide__text-link">Learn More</a></p>
</div>
</div>
</div>
<div class="slide slide-1 ">
<div class="slide__bg"></div>
<div class="slide__content">
<!--<svg class="slide__overlay" viewBox="0 0 720 405" preserveAspectRatio="xMaxYMax slice">
<path class="slide__overlay-path" d="M0,0 150,0 500,405 0,405" />
</svg>-->
<div class="slide__text">
<h2 class="slide__text-heading"><b>New</b> featured products</h2>
<h3 class="slide__text-sub-head">LCN<sup>®</sup> touchless actuators</h3>
<p class="slide__text-desc">Allegion offers no-touch actuators that are installed in place of push buttons and comply with ANSI 156.19 low energy standards. A pedestrian simply waves a hand in front of the wall plate, the technology senses the motion and acknowledges intent to enter. No contact with the door or hardware is required.<br><a class="slide__text-link">Learn More</a></p>
</div>
</div>
</div>
<div class="slide slide-2">
<div class="slide__bg"></div>
<div class="slide__content">
<!--<svg class="slide__overlay" viewBox="0 0 720 405" preserveAspectRatio="xMaxYMax slice">
<path class="slide__overlay-path" d="M0,0 150,0 500,405 0,405" />
</svg>-->
<div class="slide__text">
<h2 class="slide__text-heading"><b>New</b> featured products</h2>
<h3 class="slide__text-sub-head">Schlage<sup>®</sup> mobile access solutions</h3>
<p class="slide__text-desc">Schlage Mobile Access Solutions provide comprehensive touchless offering, including mobile enabled multi-technology readers, mobile enabled wireless electronic locks and mobile access credentials.<br><a class="slide__text-link">Learn More</a></p>
</div>
</div>
</div>
</div>
</div>
TIA!
Just tried the following which seems to have corrected the issue.
I changed this line:
numOfSlides = $(".slide").length-1,
To this:
numOfSlides = $(".slide").length-2,
Getting the desired result now...only 3 slides as intended. Hopefully the code is fundamentally sound.

JavaScript getElementById not working on mobilephone

I'm creating a website which has some JavaScript code. Everything of that JavaScript is working fine on the computer. But on my iPhone 7 the getElementById function does not work. I try to set a source of an img tag but nothing happens.
JavaScript:
var header_bar = $('.js-header-bar, .js-header-bar-mobile');
var header_bar_mobile = $('.js-header-bar-mobile');
var header_bar_navbar = header_bar_mobile.find('.navbar-primary');
var header_bar_toggler = header_bar_mobile.find('.navbar-toggler');
var header_bar_offsetTop = header_bar.offset().top;
$(window).on('scroll', onScroll);
function onScroll(){
if ($(this).scrollTop() > header_bar_offsetTop){
header_bar.addClass("sticky");
document.getElementById("headerLogo").src = "images/logo-black.png";
} else {
header_bar.removeClass("sticky");
document.getElementById('headerLogo').src = "images/logo-white.png";
}
}
The function should add at the top of the site a black logo and if I scroll a white logo.
On the computer it works but on my smartphone not.
HTML:
<header class="header header-mobile js-header-bar-mobile d-md-none">
<div class="header-bar">
<div class="header-bar-logo">
<a href="index.html">
<img class="originalTest" alt='Auto mit Schriftzug: "Autohandel-ZAR"' id="headerLogo" src="images/logo-white.png"/>
</a>
</div>
<div class="header-bar-menu">
<button class="navbar-toggler hamburger" type="button" id="js-header-toggle">
<span class="hamburger-box">
<span class="hamburger-inner"></span>
</span>
</button>
</div>
</div>
Thank you in advance.
Add an additional event listener for mobile devices:
$(document.body).on('touchmove', onScroll);
so the complete code should looks like:
var header_bar = $('.js-header-bar, .js-header-bar-mobile');
var header_bar_mobile = $('.js-header-bar-mobile');
var header_bar_navbar = header_bar_mobile.find('.navbar-primary');
var header_bar_toggler = header_bar_mobile.find('.navbar-toggler');
var header_bar_offsetTop = header_bar.offset().top;
$(document.body).on('touchmove', onScroll);
$(window).on('scroll', onScroll);
function onScroll(){
if ($(this).scrollTop() > header_bar_offsetTop){
header_bar.addClass("sticky");
document.getElementById("headerLogo").src = "images/logo-black.png";
} else {
header_bar.removeClass("sticky");
document.getElementById('headerLogo').src = "images/logo-white.png";
}
}
I solved the problem by getting the element with jQuery by class and not by Id
so the issue was the Id part.
Working Code:
function onScroll(){
if ($(this).scrollTop() > header_bar_offsetTop){
header_bar.addClass("sticky");
$(".logoHeader").attr("src", "images/logo-black.png");
} else {
header_bar.removeClass("sticky");
$(".logoHeader").attr("src", "images/logo-white.png");
}
}

Start counting after scroll on specific element

I create a website and add a counter to my codes.
$(function() {
function count($this){
var current = parseInt($this.html(), 10);
$this.html(++current);
if(current !== $this.data('count')){
setTimeout(function(){count($this)}, 50);
}
}
$(".c-section4").each(function() {
$(this).data('count', parseInt($(this).html(), 10));
$(this).html('0');
count($(this));
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div class="section4">
<div class="section4-bg"></div>
<div class="counter-section">
<span class="c-section4">152 </span>
<h3> کارکنان ما </h3>
</div>
<div class="counter-section">
<span class="c-section4">152 </span>
<h3> کارکنان ما </h3>
</div>
<div class="counter-section">
<span class="c-section4">152 </span>
<h3> کارکنان ما </h3>
</div>
</div>
Now i have a problem, i want to counter start when i scroll to this element
Demo
Sorry for my bad english
You can handle the window scroll event and use the function given here by Scott Dowding to determine if the element has been scrolled into view. An isCounting flag can be set on each element to prevent counting several times simultaneously.
In the following code snippet, the counting is performed only while the element is visible.
$(function () {
function isScrolledIntoView($elem) {
var docViewTop = $(window).scrollTop();
var docViewBottom = docViewTop + $(window).height();
var elemTop = $elem.offset().top;
var elemBottom = elemTop + $elem.height();
return ((elemBottom <= docViewBottom) && (elemTop >= docViewTop));
}
function count($this) {
var current = parseInt($this.html(), 10);
if (isScrolledIntoView($this) && !$this.data("isCounting") && current < $this.data('count')) {
$this.html(++current);
$this.data("isCounting", true);
setTimeout(function () {
$this.data("isCounting", false);
count($this);
}, 50);
}
}
$(".c-section4").each(function () {
$(this).data('count', parseInt($(this).html(), 10));
$(this).html('0');
$(this).data("isCounting", false);
});
function startCount() {
$(".c-section4").each(function () {
count($(this));
});
};
$(window).scroll(function () {
startCount();
});
startCount();
});
.tallDiv
{
height: 800px;
background-color: silver;
}
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div class="section4">
<div class="section4-bg"></div>
<div class="tallDiv">Scroll down to test</div>
<div class="counter-section">
<span class="c-section4">152 </span>
<h3> کارکنان ما </h3>
</div>
<div class="counter-section">
<span class="c-section4">152 </span>
<h3> کارکنان ما </h3>
</div>
<div class="counter-section">
<span class="c-section4">152 </span>
<h3> کارکنان ما </h3>
</div>
<div class="tallDiv"></div>
</div>
You need to give the target element and id, then get its postition from top var pos = document.getElementById('targetId').scrollHeight - element.clientHeight; and compare it to the scrolled height window.pageYOffset.
If widow offset is greater than the pos, you can start the counter. You should hook the comparison to the window.onscroll event.
Also you should memorize in a variable if you started the counter for an element already to avoid starting it twice.
Get the scroll Height and compare with the height of the start div(count start div) put a condition
$(function() {
var pos = document.getElementById('targetId').scrollHeight;
console.log(pos);
if(pos>="75"){
function count($this){
var current = parseInt($this.html(), 10);
$this.html(++current);
if(current !== $this.data('count')){
setTimeout(function(){count($this)}, 50);
}
}
$(".c-section4").each(function() {
$(this).data('count', parseInt($(this).html(), 10));
$(this).html('0');
count($(this));
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="counter-section" id="targetId">
<span class="c-section4">152 </span>
<h3> کارکنان ما </h3>
</div>
Live Link
You can use this Plugin for it. Source LINK
<span class='numscroller numscroller-big-bottom' data-slno='1' data-min='0'
data-max='82' data-delay='19' data-increment="2">0</span>
NB: data-max='**'give your max-number and data-delay='**' select a time for countdown running and select increment data-increment="**" .
/**
* jQuery scroroller Plugin 1.0
*
* http://www.tinywall.net/
*
* Developers: Arun David, Boobalan
* Copyright (c) 2014
*/
(function($){
$(window).on("load",function(){
$(document).scrollzipInit();
$(document).rollerInit();
});
$(window).on("load scroll resize", function(){
$('.numscroller').scrollzip({
showFunction : function() {
numberRoller($(this).attr('data-slno'));
},
wholeVisible : false,
});
});
$.fn.scrollzipInit=function(){
$('body').prepend("<div style='position:fixed;top:0px;left:0px;width:0;height:0;' id='scrollzipPoint'></div>" );
};
$.fn.rollerInit=function(){
var i=0;
$('.numscroller').each(function() {
i++;
$(this).attr('data-slno',i);
$(this).addClass("roller-title-number-"+i);
});
};
$.fn.scrollzip = function(options){
var settings = $.extend({
showFunction : null,
hideFunction : null,
showShift : 0,
wholeVisible : false,
hideShift : 0,
}, options);
return this.each(function(i,obj){
$(this).addClass('scrollzip');
if ( $.isFunction( settings.showFunction ) ){
if(
!$(this).hasClass('isShown')&&
($(window).outerHeight()+$('#scrollzipPoint').offset().top-settings.showShift)>($(this).offset().top+((settings.wholeVisible)?$(this).outerHeight():0))&&
($('#scrollzipPoint').offset().top+((settings.wholeVisible)?$(this).outerHeight():0))<($(this).outerHeight()+$(this).offset().top-settings.showShift)
){
$(this).addClass('isShown');
settings.showFunction.call( this );
}
}
if ( $.isFunction( settings.hideFunction ) ){
if(
$(this).hasClass('isShown')&&
(($(window).outerHeight()+$('#scrollzipPoint').offset().top-settings.hideShift)<($(this).offset().top+((settings.wholeVisible)?$(this).outerHeight():0))||
($('#scrollzipPoint').offset().top+((settings.wholeVisible)?$(this).outerHeight():0))>($(this).outerHeight()+$(this).offset().top-settings.hideShift))
){
$(this).removeClass('isShown');
settings.hideFunction.call( this );
}
}
return this;
});
};
function numberRoller(slno){
var min=$('.roller-title-number-'+slno).attr('data-min');
var max=$('.roller-title-number-'+slno).attr('data-max');
var timediff=$('.roller-title-number-'+slno).attr('data-delay');
var increment=$('.roller-title-number-'+slno).attr('data-increment');
var numdiff=max-min;
var timeout=(timediff*1000)/numdiff;
//if(numinc<10){
//increment=Math.floor((timediff*1000)/10);
//}//alert(increment);
numberRoll(slno,min,max,increment,timeout);
}
function numberRoll(slno,min,max,increment,timeout){//alert(slno+"="+min+"="+max+"="+increment+"="+timeout);
if(min<=max){
$('.roller-title-number-'+slno).html(min);
min=parseInt(min)+parseInt(increment);
setTimeout(function(){numberRoll(eval(slno),eval(min),eval(max),eval(increment),eval(timeout))},timeout);
}else{
$('.roller-title-number-'+slno).html(max);
}
}
})(jQuery);
.nm {
height: 400px;
background: #f5f5f5;
display: block;
}
.nm_1 {
background-color: #632525;
}
.nm_2 {
background-color: grad;
}
.nm_3 {
background-color: gray;
}
.nm_4 {
background-color: green;
}
.nm_5 {
background-color: georgian;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="nm nm_1">
</section>
<section class="nm nm_2">
</section>
<section class="nm nm_3">
</section>
<section class="nm nm_4">
<div>
<span class='numscroller numscroller-big-bottom' data-slno='1' data-min='0' data-max='192' data-delay='19' data-increment="2">0</span>
<h3> کارکنان ما </h3>
</div>
<div>
<span class='numscroller numscroller-big-bottom' data-slno='1' data-min='0' data-max='282' data-delay='19' data-increment="2">0</span>
<h3> کارکنان ما </h3>
</div>
<div>
<span class='numscroller numscroller-big-bottom' data-slno='1' data-min='0' data-max='82' data-delay='19' data-increment="2">0</span>
<h3> کارکنان ما </h3>
</div>
</section>
<section class="nm nm_4">
</section>
<section class="nm nm_5">
</section>
Here's my solution which supports floats and a configurable animation duration. It will only animate the count one time - as soon the element appears in the viewport of the specified container.
const initAnimatedCounts = () => {
const ease = (n) => {
// https://github.com/component/ease/blob/master/index.js
return --n * n * n + 1;
};
const observer = new IntersectionObserver((entries) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
// Once this element is in view and starts animating, remove the observer,
// because it should only animate once per page load.
observer.unobserve(entry.target);
const countToString = entry.target.getAttribute('data-countTo');
const countTo = parseFloat(countToString);
const duration = parseFloat(entry.target.getAttribute('data-animateDuration'));
const countToParts = countToString.split('.');
const precision = countToParts.length === 2 ? countToParts[1].length : 0;
const startTime = performance.now();
const step = (currentTime) => {
const progress = Math.min(ease((currentTime - startTime) / duration), 1);
entry.target.textContent = (progress * countTo).toFixed(precision);
if (progress < 1) {
animationFrame = window.requestAnimationFrame(step);
} else {
window.cancelAnimationFrame(animationFrame);
}
};
let animationFrame = window.requestAnimationFrame(step);
}
});
});
document.querySelectorAll('[data-animateDuration]').forEach((target) => {
target.setAttribute('data-countTo', target.textContent);
target.textContent = '0';
observer.observe(target);
});
};
initAnimatedCounts();
div {
font-size: 30px;
text-align: center;
padding: 30px 0;
}
div > span {
color: #003d82;
}
div.scrollpad {
height: 100vh;
background-color: #eee;
}
<div>
<span>$<span data-animateDuration="1000">987.45</span></span> was spent on
about <span><span data-animateDuration="1000">5.8</span>M</span> things.
</div>
<div class="scrollpad">keep scrolling</div>
<div>
There are <span><span data-animateDuration="1000">878</span>K</span> people involved.
<br/>
And <span><span data-animateDuration="1000">54</span></span> cakes.
</div>
<div class="scrollpad">keep scrolling</div>
<div>
Additionally, <span>$<span data-animateDuration="3000">300</span>B</span> went to waste.
<br/>
Because <span>$<span data-animateDuration="2000">54</span></span> was spent on each cake.
</div>
<div class="scrollpad">keep scrolling</div>
<div>
Lastly, <span><span data-animateDuration="4000">3.5334583</span>T</span> ants said hello.
<br/>
But <span><span data-animateDuration="2000">4</span></span> of them said goodbye.
</div>

How to scroll the div content using jquery or javascript?

I want to scroll the div, containing the text, to the top when I mouseover the up arrow and stop when the mouse leaves the focus. Same for the down arrow.
I tried using jquery but it fails.
please visit: http://jsfiddle.net/shantanubhaware/38WMF/12/
Here is Html code
<div class="container">
<div class="news event">
<div class="up arrow nav"></div>
<div class="down arrow nav"></div>
<p class="content items"> <span class="p">text1
<br/>
<br/>
<br/><br/>
<br/><br/>
<br/><br/><br/><br/><br/>
text2
<br/>
<br/>
<br/><br/>
<br/><br/>
<br/><br/><br/><br/><br/>
text3
<br/>
<br/>
<br/><br/>
<br/><br/>
<br/><br/><br/><br/><br/>
text4</span>
</p>
</div>
</div>
I use the following jquery
$('.up').mouseover(function () {
scrollToTop();
});
$('.down').mouseover(function () {
scrollToBottom();
});
function scrollToTop() {
var cur = $('.content').scrollTop();
while (cur > 0) {
cur = parseInt(cur) - 50;
$('.content').animate({
scrollTop: cur
}, 800);
}
}
function scrollToBottom() {
var cur = $('.content').scrollTop();
var height = $('.p').height();
while (cur < height) {
cur = parseInt(cur) + 50;
$('.content').animate({
scrollTop: cur
}, 800);
}
}
tell me if i am wrong anywhere or if i want to use any other technique.
Thanks for your support.
you need to stop the ongoing animation before starting a new one, otherwise it will finish the ongoing animation first and only then will start the new one.
its done by calling .stop() first.
also you forgot to bind on mouse leave events.
heres yours fixed fiddle:
http://jsfiddle.net/TheBanana/38WMF/14/

Categories