Javascript move down scrollbar using element not working - javascript

Hey all I have the html code below that should allow the page to scroll all the way down to the nextChatHolder element when you push the button.
It adds the chat bubble just fine at the bottom but I want it to scroll down to the nextChatHolder each time I press the button.
I have no errors and these examples work standalone. So naturally there somewhere in my javascript or css that is causing it not to scroll - and I am unable to find what that it!
Visual: https://jsbin.com/xihosicayo/edit?js,output
function getElementY(query) {
return window.pageYOffset + document.querySelector(query).getBoundingClientRect().top;
}
function scrollToItem(item) {
var diff = (item.offsetTop-window.scrollY)/8;
if (Math.abs(diff) > 1) {
window.scrollTo(0, (window.scrollY+diff));
clearTimeout(window._TO);
window._TO=setTimeout(scrollToItem, 30, item);
} else {
window.scrollTo(0, item.offsetTop);
}
}
function doScrolling(element, duration) {
var startingY = window.pageYOffset
var elementY = getElementY(element)
var targetY = document.body.scrollHeight - elementY < window.innerHeight ? document.body.scrollHeight - window.innerHeight : elementY
var diff = targetY - startingY
var easing = function (t) { return t<.5 ? 4*t*t*t : (t-1)*(2*t-2)*(2*t-2)+1; }
var start;
if (!diff) return
window.requestAnimationFrame(function step(timestamp) {
if (!start) start = timestamp;
var time = timestamp - start;
var percent = Math.min(time / duration, 1);
percent = easing(percent);
window.scrollTo(0, startingY + diff * percent);
if (time < duration) {
window.requestAnimationFrame(step);
}
})
}
function newTalk(textVal, pic) {
var my_elem = document.getElementById("nextChatHolder");
var div = document.createElement('div');
div.innerHTML = '<div class="animated animatedFadeInUp fadeInUp">' +
'<div class="chat self">' +
'<div class="user-photo">' +
'<img src="' + pic + '">' +
'</div>' +
'<p class="chat-message">' + textVal + '</p>' +
'<span class="timeself">11:01 PM | Oct 11 2019</span>' +
'</div>' +
'</div>';
my_elem.parentNode.insertBefore(div, my_elem);
//scrollToItem(my_elem))
}

I believe you're looking for:
my_elem.scrollIntoView({behavior: "smooth",block: "end"})
as the last line in newTalk.
Documentation

Related

Can't change css style with JS

<script>
var animate = function (element, target, callback) {
clearInterval(element.timer);
element.timer = setInterval(function () {
var step = (target - element.offsetLeft) / 10;
step = step > 0 ? Math.ceil(step) : Math.floor(step);
element.style.left = element.offsetLeft + step + 'px';
// console.log(element.offsetLeft);
if (element.offsetLeft == target) {
clearInterval(element.timer);
callback && callback();
}
}, 20)
};
window.addEventListener('load', function () {
var ul = document.querySelector('.local-nav');
console.log(ul);
for (var i = 0; i < ul.children.length; i++) {
ul.children[i].children[0].children[0].style.backgroundPosition = '0 ' + -i * 32 + 'px';
}
var ul2 = document.querySelector('.subnav-entry ul');
console.log(ul2);
for (var i = 0; i < ul2.children.length; i++) {
console.log(ul2.children[i].children[0].children[0]);
ul2.children[i].children[0].children[0].style.backgroundPosition = '0 ' + -i * 32 + 'px';
}
var focus_ul = document.querySelector('.focus ul');
var ol = document.querySelector('.focus ol');
var count = 0;
var focus_timer = setInterval(function () {
if (count == 2) {
animate(focus_ul, focus_ul.offsetLeft - 375);
// console.log('i run');
// console.log(focus_ul.offsetLeft + ' ' + count);
// focus_ul.style.left = focus_ul.offsetLeft + 375 * 2 + 'px';
focus_ul.style.left = 0 + 'px'; // Here is my problem
console.log(focus_ul);
console.log(focus_ul.offsetLeft + ' ' + count);
}
else {
console.log('before animation ' + focus_ul.offsetLeft + ' ' + count);
animate(focus_ul, focus_ul.offsetLeft - 375);
console.log(focus_ul.offsetLeft + ' ' + count);
}
// focus_ul.style.left = focus_ul.offsetLeft + 375 + 'px';
count++;
count = count % 3;
for (var i = 0; i < ol.children.length; i++) {
ol.children[i].className = '';
}
ol.children[count].className = 'current-choice';
console.log('after a round ' + focus_ul.offsetLeft + ' ' + count);
}, 2500)
})
</script>
I meant to do a photo show that can play automaticly, like a Carousel or swiper, The 375px means that the screen is 375px wide, according to the code, when comming to the last photo, as the animation end, it should change back to the initial one which style.left == 0px, but 0px only occur a small while, next time it would be -1125px, -1500px and so on, I'm confused why i set style.left to 0 but fruitless. I'm new in front end ,thanks helping
You can use more of CSS (and less JavaScript) for this animation.
Declare two separate CSS class definitions for focus_ul. Use JavaScript to change the className of focus_ul.
Use CSS transition for animation of CSS offset-left property.
See: https://www.w3schools.com/css/tryit.asp?filename=trycss3_transition1
Write that custom className instead :hover in above example.

How to stop infinite loop in subtle-slidershow.js?

how can I stop the infinite loop of the following Ken-Burns-Slider-script? I have 3 pictures and I would like to stop the slider after animation of the third picture. Try with stop() of slideRefresh did not work (or my coding was bad).
The full code of the script can be seen on GitHub. Thanks for your help.
(function($){
$.fn.slideshow = function(options){
var slides = $(this);
var settings = $.extend({
randomize: true,
slideDuration: 6000,
fadeDuration: 1000,
animate: true,
slideElementClass: 'slide',
slideshowId: 'slideshow'
}, options);
}
$('<div id="' + settings.slideshowId + '"></div>').insertBefore(slides);
var slideshow = $('#' + settings.slideshowId);
var slideTimeDelta = 0;
var resumeStartTime = 0;
var resumeTimer;
if(settings.animate == true){
var cssAnimationDuration = settings.slideDuration + settings.fadeDuration;
}else{
slides.find('.' + settings.slideElementClass + ' span.animate').removeClass('animate');
var cssAnimationDuration = 0;
}
console.log('Slideshow initialized.');
slides.find('.' + settings.slideElementClass + ':first span.animate').addClass('active').css('animation-duration', cssAnimationDuration + 'ms')
slides.find('.' + settings.slideElementClass + ':first').prependTo(slideshow);
var currentSlideStartTime = Date.now();
// Start interval loop
slidesInterval = setInterval(slideRefresh, settings.slideDuration);
console.log('Slideshow started.');
if(settings.pauseOnTabBlur == true){
$(window).focus(function() {
console.log('Window gained focus.');
if (paused == true) {
console.log('Resuming slideshow.');
resumeStartTime = Date.now();
paused = false;
$('#' + settings.slideshowId + ' span.active:last').removeClass('paused');
resumeTimer = setTimeout(function(){
slideTimeDelta = 0;
slideRefresh();
slidesInterval = setInterval(slideRefresh, settings.slideDuration);
}, settings.slideDuration - slideTimeDelta);
}
}).blur(function() {
paused = true;
console.log('Window lost focus, slideshow paused.');
if(slideTimeDelta != 0){
var timeSinceLastPause = Date.now() - resumeStartTime;
slideTimeDelta = slideTimeDelta + timeSinceLastPause;
console.log('Time since last pause within this slide: ' + timeSinceLastPause + ' ms');
}else{
slideTimeDelta = Date.now() - currentSlideStartTime;
}
console.log('Current slide at ' + slideTimeDelta + ' ms.');
$('#' + settings.slideshowId + ' span.active:first').addClass('paused');
clearInterval(slidesInterval);
clearTimeout(resumeTimer);
});
}
function slideRefresh() {
console.log('Slide refresh triggered.');
currentSlideStartTime = Date.now();
var slideshowDOM = slideshow[0];
if(slideshowDOM.children.length == 0) {
console.log('There are no slides in the slideshow.');
slides.find('.' + settings.slideElementClass + ':first').prependTo(slideshow);
}else{
slides.find('.' + settings.slideElementClass + ':first').prependTo(slideshow);
var slideElement = '#' + settings.slideshowId + ' .' + settings.slideElementClass;
$(slideElement + ':first span.animate').addClass('active').css('animation-duration', cssAnimationDuration + 'ms');
$(slideElement + ':last').fadeOut(settings.fadeDuration, function(){
$(slideElement + ':last span.animate').removeClass('active').css('animation-duration', '0ms');
$(slideElement + ':last').appendTo(slides);
slides.find('.' + settings.slideElementClass).show(0);
});
}
}
};
}( jQuery ));

Javascript loop through date/times in vali increments

I've trying to build out a table from a start time until the end of day in defined increments.
eg: if the user selects 15 minute increment starting from 8:10am, the times goes
8:10,8:25,8:40,8:55,9:10...
My current code does not correct work out we've changed to the next hour and then start the offset again, eg i get:
815,830,845,905,935,1025,1125,1225,1325...
Here is a JSFiddle
https://jsfiddle.net/inboxdesign/c8f2dhng/13/
Here is the code I have so far;
// from select:
let $first_hour = 8;
let $first_minute = 10;
let day_count = 1; // don't worry about this;
let duration = 15; // increment
var offset = 0;
var current_time = parseInt($first_hour + $first_minute);
for (var i = 0; i < 120; i++) {
if (current_time < 2400) {
var time_string = ('' + current_time);
var time_minutes = parseInt(time_string.substring(time_string.length - 2));
if (time_minutes < 60) {
// offset = 0;
times += '<tr>';
for (var d = 1; d <= day_count; d++) {
times += '<td>d: ' + d + ' : time: ' + current_time + ' ->' + time_string.substring(time_string.length - 2) + ' offset: ' + offset +'</td>';
}
times += '</tr>';
} else {
offset = (time_minutes - 60);
// times += '<tr>';
// times += '<td>o:' + offset + ' tm: ' + time_minutes + '</td>';
// time_minutes = offset;
// times += '</td>';
}
}
console.log('current_time: ' + current_time);
current_time = parseInt(current_time + duration + offset);
In this line your else offset has to be reset to 0
for (var d = 1; d <= SP.new_conference.day_count; d++) {
times += '<td>d: ' + d + ' : time: ' + current_time + ' ->' + time_minutes + ' offset: ' + offset +'</td>';
}
// times += '</tr>';
} else {
offset = 0;
and then your current time and offset should look like this
current_time = parseInt(current_time + SP.new_conference.duration );
offset+=SP.new_conference.duration
I have fixed this issues in the jsfiddle if you want to have a look

Transform HH MM SS in seconds

I need to transform 3 form inputs (HH, MM, SS) in seconds with javascript.
I have this code but it has only with 1 form input in seconds : https://jsfiddle.net/94150148/hhomeLc3/
To do this I need a new javascript function.
window.onload = function () {generate()};
function generate() {
var width = 'width=\"' + document.getElementById('width').value + '\" ';
var height = 'height=\"' + document.getElementById('height').value + '\" ';
var ytid = "videoID";
var start = document.getElementById('start').value;
var end = document.getElementById('end').value;
if (start !== "") {
if(ytid === document.getElementById('ytid')) {
ytid += '?start=' + start;
}
else {
ytid += '&start=' + start;
}
}
if (end !== "") {
if (ytid === document.getElementById('ytid')) {
ytid += '?end=' + end;
}
else {
ytid += '&end=' + end;
}
}
document.getElementById('embedcode').value = '<iframe ' + width + height +
'src=\"https://www.youtube.com\/embed\/' + ytid +
'\" frameborder=\"0\"><\/iframe>';
}
function clearall() {
document.getElementById('width').value = 550;
document.getElementById('height').value = 315;
document.getElementById('start').value = "";
document.getElementById('end').value = "";
}
The jsFiddle to play with what I need : https://jsfiddle.net/94150148/ybmkcyyu/
https://jsfiddle.net/ybmkcyyu/3/
EDIT:
Do not display start and end when value is 0
https://jsfiddle.net/ybmkcyyu/6/
EDIT2:
https://jsfiddle.net/ybmkcyyu/7/
if (start !== "") {
ytid += '?start=' + start;
}
if (end !== "") {
if (start == "") {
ytid += '?end=' + end;
}
else {
ytid += '&end=' + end;
}
}
You just need to get value of every fields, as int, then add it with the formula: ((hours * 60) + minutes ) * 60 + secondes
And you might ensure that the result is a number. (if user enter a char instead of a number, it should not display something wrong)
var starth = parseInt(document.getElementById('starth').value);
var startm = parseInt(document.getElementById('startm').value);
var starts = parseInt(document.getElementById('starts').value);
var endh = parseInt(document.getElementById('endh').value);
var endm = parseInt(document.getElementById('endm').value);
var ends = parseInt(document.getElementById('ends').value);
var start = (((starth * 60) + startm) * 60) + starts;
if(isNaN(start) || start === 0)
start = "";
var end = (((endh * 60) + endm) * 60) + ends;
if(isNaN(end) || end === 0)
end = "";
/* (...) */
JS is generally quite good at math.
sHour = document.getElementById('starth').value,
sMin = document.getElementById('startm').value,
sSec = document.getElementById('starts').value,
sTime = (sHour * 3600) + (sMin * 60) + sSec;
https://jsfiddle.net/link2twenty/ybmkcyyu/4/

Zoom into a specific point on an image using mousewheel

I am attempting to build an image zoom/panner using JS/jQuery. I have so far managed to get the zoom working using the mousewheel to zoom in/out, but it currently only zooms in on the center point each time.
Like with Google maps I want to be able to zoom in on the point where the mouse cursor is, but am unsure on the code to do this.
I have setup a fiddle with my progress so far:
http://jsfiddle.net/quirksmode/XrKLN/1/
Any help would be massively appreciated :-)
My code is:
// Plugin to allow for button holds
jQuery.fn.mousehold = function (timeout, f) {
if (timeout && typeof timeout == 'function') {
f = timeout;
timeout = 100;
}
if (f && typeof f == 'function') {
var timer = 0;
var fireStep = 0;
return this.each(function () {
jQuery(this).mousedown(function () {
fireStep = 1;
var ctr = 0;
var t = this;
timer = setInterval(function () {
ctr++;
f.call(t, ctr);
fireStep = 2;
}, timeout);
})
clearMousehold = function () {
clearInterval(timer);
if (fireStep == 1) f.call(this, 1);
fireStep = 0;
}
jQuery(this).mouseout(clearMousehold);
jQuery(this).mouseup(clearMousehold);
})
}
}
/**
* CSS3 Transform helper
*/
var cssTransformScale = function (x, y, z) {
return {
'-webkit-transform': 'scale3d(' + x + ', ' + y + ', ' + z + ')',
'-moz-transform': 'scale3d(' + x + ', ' + y + ', ' + z + ')',
'-ms-transform': 'scale3d(' + x + ', ' + y + ', ' + z + ')',
'-o-transform': 'scale3d(' + x + ', ' + y + ', ' + z + ')',
'transform': 'scale3d(' + x + ', ' + y + ', ' + z + ')',
};
};
$(document).ready(function () {
var assetViewer = {
name: 'assetViewer',
defaults: {
$assetWrap: $('#asset-wrap'),
$assetImg: $('.asset-img'),
imgSrc: "http://lorempixel.com/1600/760/",
zoomScale: 0.01,
initialZoom: 1,
currentZoom: 1,
maxZoom: 3,
minZoom: 1,
$zoomIn: $('#zoom-in'),
$zoomOut: $('#zoom-out')
},
init: function (options) {
var me = this;
this.options = $.extend(this.defaults, options);
this.appendImage();
this.bindEvents();
},
appendImage: function () {
var me = this;
this.options.$assetWrap.append('<div class="asset-holder"><div class="asset-inner-wrap"><img class="asset-img" src="' + this.options.imgSrc + '" /></div></div>');
me.options.$assetImg = $(me.options.$assetImg.selector); // Using .selector to refresh the element
},
bindEvents: function () {
var me = this;
me.options.$zoomIn.mousehold(1, function () {
me.zoom("+", 1);
})
me.options.$zoomOut.mousehold(1, function () {
me.zoom("-", 1);
})
me.options.$assetImg.mousewheel(function (event, delta) {
if (delta > 0) me.zoom("+", delta);
else if (delta < 0) me.zoom("-", Math.abs(delta)); // Forces the negative to become a positive
return false; // prevent default
});
},
zoom: function (direction, delta) {
var me = this;
//console.log();
if ((me.options.currentZoom >= me.options.minZoom) && (me.options.currentZoom <= me.options.maxZoom)) {
var scale = (direction === "+") ? me.options.currentZoom += (me.options.zoomScale * delta) : me.options.currentZoom -= (me.options.zoomScale * delta);
// Set the Zoom Bounds
if (me.options.currentZoom <= me.options.minZoom) {
scale = me.options.currentZoom = me.options.minZoom;
}
if (me.options.currentZoom >= me.options.maxZoom) {
scale = me.options.currentZoom = me.options.maxZoom;
}
me.options.$assetImg.css(cssTransformScale(scale, scale, scale));
}
}
}
assetViewer.init();
});
I have done something very similar to what you are trying to achieve and I have a div within a div and then used the left and top CSS attributes of the child div to navigate around the image via a minimap image.

Categories