Sticky box jQuery - javascript

I have this code:
http://jsfiddle.net/k56yR/1/
but when the browser scrollbar is down and begin to top #sticky trembles, anyone know how to fix this?
This is jQuery code:
$(function(){ // document ready
if (!!$('#sticky').length) { // make sure "#sticky" element exists
var el = $('#sticky');
var stickyTop = $('#sticky').offset().top; // returns number
var footerTop = $('#footer').offset().top; // returns number
var stickyHeight = $('#sticky').height();
var limit = footerTop - stickyHeight - 20;
$(window).scroll(function(){ // scroll event
var windowTop = $(window).scrollTop(); // returns number
if (stickyTop < windowTop){
el.css({ position: 'fixed', top: 0 });
}
else {
el.css('position','static');
}
if (limit < windowTop) {
var diff = limit - windowTop;
el.css({top: diff});
}
});
}
});​

<div class="wrapper">
<div class="results">
</div>
<header>
Header
<span></span>
</header>
<div class="left">
<span class="top"></span>
<div class="nosticky">Nosticky</div>
<div class="sticky">
<span class="top"></span>
<div class="bloc bloc1">
Bloc 1<br>
<span></span>
</div>
<div class="bloc bloc2">
Bloc 2
</div>
<span class="bottom"></span>
</div>
<span class="bottom"></span>
</div>
<div class="right">
Content
<span></span>
</div>
<div class="footer">
Footer
</div>
</div>
<script>
var sticky_offsettop = $('.sticky').offset().top;
var sticky_height = $('.sticky').height();
var sidebar_height = $('.left').height();
var empty_space_left = sidebar_height - sticky_height;
var sidebar_offsettop = $('.left').offset().top;
var sidebar_bottom_offsettop = (sidebar_offsettop+sidebar_height);
var margintotop = 20;
$(window).scroll(function() {
var window_scrolltop = $(window).scrollTop();
var window_scrolltop_margin = (window_scrolltop+margintotop);
var realtime_sidebar_bottom_offsettop = (sidebar_bottom_offsettop - window_scrolltop);
var sticky_height_realtime = $('.sticky').height();
if(window_scrolltop_margin >= sticky_offsettop ){
$('.bloc').css('background', '#ddd');
$('.sticky').css('position', 'sticky').css('top', '20px').css('bottom', 'initial');
}
if(sticky_offsettop > window_scrolltop_margin ){
$('.bloc').css('background', '#ddd');
$('.sticky').css('position', 'relative').css('top', 'initial').css('bottom', 'initial');
}
if(sticky_height_realtime >= realtime_sidebar_bottom_offsettop ){
$('.bloc').css('background', '#ddd');
$('.sticky').css('position', 'absolute').css('top', 'initial').css('position', 'absolute').css('bottom', '0');
}
});
<script>
here is an example i've done to achieve it : https://jsfiddle.net/cuopyL51/

Related

How to detect correct div data attribute when each hitting the top of the page

I am working on the below code. Why am I not able to detect which div is reaching at the top of page in both down or up scroll?
$(window).scroll(function() {
$(".container").each(function() {
var $that = $(this);
var po = $(this).offset().top;
if (po >= 0 && po <= 300) {
console.log($that.data('map'));
}
});
});
.container {
height: 690px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" data-map="One">One</div>
<div class="container" data-map="Two">Tow</div>
<div class="container" data-map="Three">Three</div>
<div class="container" data-map="Four">Four</div>
<div class="container" data-map="Five">Five</div>
You'll need to use $(window).scrollTop(); as well as $that.outerHeight()
$(window).scroll(function() {
var windowScrollTop = $(this).scrollTop(); // window scroll top
$(".container").each(function() {
var $that = $(this);
var po = $that.offset().top;
var poHeight = $that.outerHeight(true); // the height of the element
var distanceTop = 100; // the distance from top to run the action .. it can be 0 if you want to run the action when the element hit the 0 top
if (windowScrollTop + distanceTop >= po && windowScrollTop + distanceTop <= po + poHeight) {
if(!$that.hasClass('red')){ // if element dosen't has class red
console.log($that.data('map'));
$(".container").not($that).removeClass('red'); // remove red class from all
$that.addClass('red'); // add red class to $that
}
}
});
}).scroll(); // run the scroll onload
.container {
height: 690px;
}
.container.red{
background : red;
color : #fff;
font-size: 30px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container" data-map="One">One</div>
<div class="container" data-map="Two">Two</div>
<div class="container" data-map="Three">Three</div>
<div class="container" data-map="Four">Four</div>
<div class="container" data-map="Five">Five</div>

In my React.js project i Used some code in the JS file to add slider on my web page TypeError: Cannot read property 'style' of undefined

I am facing this actually I do not understand the actual error is where and which terms I am missing.
I have tried to fix it out, in the console at chrome browser, it locates an error at the started marked line I have given in my snippet.
slide[current].style.display = 'block'; this is actual line I found in the browser getting error
export default function Slider() {
let slide = document.querySelectorAll('.slide');
var current = 0;
function cls(){
for(let i = 0; i < slide.length; i++){
slide[i].style.display = 'none';
}
}
function next(){
cls();
if(current === slide.length-1) current = -1;
current++;
**slide[current].style.display = 'block';**
slide[current].style.opacity = 0.4;
var x = 0.4;
var intX = setInterval(function(){
x+=0.1;
slide[current].style.opacity = x;
if(x >= 1) {
clearInterval(intX);
x = 0.4;
}
}, 100);
}
function prev(){
cls();
if(current === 0) current = slide.length;
current--;
slide[current].style.display = 'block';
slide[current].style.opacity = 0.4;
var x = 0.4;
var intX = setInterval(function(){
x+=0.1;
slide[current].style.opacity = x;
if(x >= 1) {
clearInterval(intX);
x = 0.4;
}
}, 100);
}
function start(){
cls();
slide[current].style.display = 'block';
}
start();
return (
<div>
<div class="container">
<div class="arrow l" onclick="prev()">
<img src={s1.jpg} alt="l" />
</div>
<div class="slide slide-1">
<div class="caption">
<h3>New York</h3>
<p>We love the Big Apple!</p>
</div>
</div>
<div class="slide slide-2">
<div class="caption">
<h3>Los Angeles</h3>
<p>LA is always so much fun!</p>
</div>
</div>
<div class="slide slide-3">
<div class="caption">
<h3>Bahar Dar</h3>
<p>Thank you, Bahar Dar!</p>
</div>
</div>
<div class="arrow r" onclick="next()">
<img src={s2.jpg} alt="r" />
</div>
</div>
</div>
)
}

zoom in zoom out image on scrolling in javascript

I created tabs with image.When I scroll on the image it will zoom in and zoom out. But I am facing the problem,in only first tab it is working with function zoom in & zoom out(when i scroll).I didn't get what i'm doing wrong.
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>zoom</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>
<style type="text/css">
ul li{
padding: 10px;
}
</style>
</head>
<body>
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3">
<div class="panel panel-primary">
<div class="panel-heading">
<h3 class="panel-title">Panel title</h3>
<span class="pull-right">
<!-- Tabs -->
<ul class="nav panel-tabs">
<li class="active">Tab 1</li>
<li>Tab 2</li>
<li>Tab 3</li>
<li>Tab 4</li>
</ul>
</span>
</div>
<div class="panel-body">
<br />
<br />
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<div class="container">
<div class="slide">
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab2">
<div class="container">
<div class="slide">
<img class='zoom' src='abc.jpg' alt='abc' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab3">
<div class="container">
<div class="slide">
<img class='zoom' src='xy.jpg' alt='xy' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
<div class="tab-pane" id="tab4">
<div class="container">
<div class="slide">
<img class='zoom' src='rec.png' alt='rec' width='555' height='320'/>
</div>
</div>
<br />
<!-- <input type="button" value="click me"> -->
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- <img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/>
<br />
<img class='zoom' src='daisy.jpg' alt='Daisy!' width='555' height='320'/> -->
<script src="wheelzoom.js"></script>
<script>
wheelzoom(document.querySelector('img.zoom'));
</script>
</body>
</html>
wheelzoom.js
window.wheelzoom = (function(){
var defaults = {
zoom: 0.10,
maxZoom: false,
initialZoom: 1,
};
var main = function(img, options){
if (!img || !img.nodeName || img.nodeName !== 'IMG') { return; }
var settings = {};
var width;
var height;
var bgWidth;
var bgHeight;
var bgPosX;
var bgPosY;
var previousEvent;
var cachedDataUrl;
function setSrcToBackground(img) {
img.style.backgroundRepeat = 'no-repeat';
img.style.backgroundImage = 'url("'+img.src+'")';
cachedDataUrl = 'data:image/svg+xml;base64,'+window.btoa('<svg xmlns="http://www.w3.org/2000/svg" width="'+img.naturalWidth+'" height="'+img.naturalHeight+'"></svg>');
img.src = cachedDataUrl;
}
function updateBgStyle() {
if (bgPosX > 0) {
bgPosX = 0;
} else if (bgPosX < width - bgWidth) {
bgPosX = width - bgWidth;
}
if (bgPosY > 0) {
bgPosY = 0;
} else if (bgPosY < height - bgHeight) {
bgPosY = height - bgHeight;
}
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
}
function reset() {
bgWidth = width;
bgHeight = height;
bgPosX = bgPosY = 0;
updateBgStyle();
}
function onwheel(e) {
var deltaY = 0;
e.preventDefault();
if (e.deltaY) { // FireFox 17+ (IE9+, Chrome 31+?)
deltaY = e.deltaY;
} else if (e.wheelDelta) {
deltaY = -e.wheelDelta;
}
// As far as I know, there is no good cross-browser way to get the cursor position relative to the event target.
// We have to calculate the target element's position relative to the document, and subtrack that from the
// cursor's position relative to the document.
var rect = img.getBoundingClientRect();
var offsetX = e.pageX - rect.left - window.pageXOffset;
var offsetY = e.pageY - rect.top - window.pageYOffset;
// Record the offset between the bg edge and cursor:
var bgCursorX = offsetX - bgPosX;
var bgCursorY = offsetY - bgPosY;
// Use the previous offset to get the percent offset between the bg edge and cursor:
var bgRatioX = bgCursorX/bgWidth;
var bgRatioY = bgCursorY/bgHeight;
// Update the bg size:
if (deltaY < 0) {
bgWidth += bgWidth*settings.zoom;
bgHeight += bgHeight*settings.zoom;
} else {
bgWidth -= bgWidth*settings.zoom;
bgHeight -= bgHeight*settings.zoom;
}
if (settings.maxZoom) {
bgWidth = Math.min(width*settings.maxZoom, bgWidth);
bgHeight = Math.min(height*settings.maxZoom, bgHeight);
}
// Take the percent offset and apply it to the new size:
bgPosX = offsetX - (bgWidth * bgRatioX);
bgPosY = offsetY - (bgHeight * bgRatioY);
// Prevent zooming out beyond the starting size
if (bgWidth <= width || bgHeight <= height) {
reset();
} else {
updateBgStyle();
}
}
function drag(e) {
e.preventDefault();
bgPosX += (e.pageX - previousEvent.pageX);
bgPosY += (e.pageY - previousEvent.pageY);
previousEvent = e;
updateBgStyle();
}
function removeDrag() {
document.removeEventListener('mouseup', removeDrag);
document.removeEventListener('mousemove', drag);
}
// Make the background draggable
function draggable(e) {
e.preventDefault();
previousEvent = e;
document.addEventListener('mousemove', drag);
document.addEventListener('mouseup', removeDrag);
}
function load() {
var initial = Math.max(settings.initialZoom, 1);
if (img.src === cachedDataUrl) return;
var computedStyle = window.getComputedStyle(img, null);
width = parseInt(computedStyle.width, 10);
height = parseInt(computedStyle.height, 10);
bgWidth = width * initial;
bgHeight = height * initial;
bgPosX = -(bgWidth - width)/2;
bgPosY = -(bgHeight - height)/2;;
setSrcToBackground(img);
img.style.backgroundSize = bgWidth+'px '+bgHeight+'px';
img.style.backgroundPosition = bgPosX+'px '+bgPosY+'px';
img.addEventListener('wheelzoom.reset', reset);
img.addEventListener('wheel', onwheel);
img.addEventListener('mousedown', draggable);
}
var destroy = function (originalProperties) {
img.removeEventListener('wheelzoom.destroy', destroy);
img.removeEventListener('wheelzoom.reset', reset);
img.removeEventListener('load', load);
img.removeEventListener('mouseup', removeDrag);
img.removeEventListener('mousemove', drag);
img.removeEventListener('mousedown', draggable);
img.removeEventListener('wheel', onwheel);
img.style.backgroundImage = originalProperties.backgroundImage;
img.style.backgroundRepeat = originalProperties.backgroundRepeat;
img.src = originalProperties.src;
}.bind(null, {
backgroundImage: img.style.backgroundImage,
backgroundRepeat: img.style.backgroundRepeat,
src: img.src
});
img.addEventListener('wheelzoom.destroy', destroy);
options = options || {};
Object.keys(defaults).forEach(function(key){
settings[key] = options[key] !== undefined ? options[key] : defaults[key];
});
if (img.complete) {
load();
}
img.addEventListener('load', load);
};
// Do nothing in IE9 or below
if (typeof window.btoa !== 'function') {
return function(elements) {
return elements;
};
} else {
return function(elements, options) {
if (elements && elements.length) {
Array.prototype.forEach.call(elements, main, options);
} else if (elements && elements.nodeName) {
main(elements, options);
}
return elements;
};
}
}());
When i scroll it is zoom in and zoom out but only in first tab.What I did wrong,i can't understand.Please help me.Thank you.
Nice work i worked it out and find that you are using wheelzoom(document.querySelector('img.zoom')); here in this code you are using querySelector where this code will return only one element not all element instead of this code you need to use wheelzoom(document.querySelectorAll('img.zoom')); then your example will work . I have tried and its working

Dynamic ScrollTo function requires next element

Please have a look at my example.
I have multiple rows on my website and a scrollto() button, wich is always at the bottom of the screen.
Depending on where the usere is located on my site at a certain moment, I would like him to move to the next row after he clicked the button.
I am aware of how to make a user scrollto(), but I have no clue what kind of selector I should use.
function myFunction() {
var winScroll = window.scrollTop; // current scroll of window
// find closest div
var rows = document.querySelectorAll('.row');
var closest = rows[0]; // first section
var closest_idx = 0;
var min = closest.offsetTop - winScroll;
rows.forEach(function(row, index) {
var divTopSpace = row.offsetTop - winScroll;
if( divTopSpace < min && divTopSpace > 0 ) {
closest = row;
closest_idx = index;
min = divTopSpace;
}
});
var next_idx = closest_idx + 1;
if (next_idx == rows.length) {
next_idx = 0;
}
console.log(rows[next_idx]);
}
.rowOne {
height: 100vh;
background-color: peachpuff;
}
.rowTwo {
height: 100vh;
background-color: firebrick;
}
.rowThree {
height: 100vh;
background-color: deepskyblue;
}
.btn {
position: fixed;
bottom: 0;
left: 0;
right: 0;
height: 30px;
}
<div class="main">
<div class="row rowOne">
<div class="a">
<div class="b">
Foo
</div>
</div>
</div>
<div class="row rowTwo">
<div class="a">
<div class="b">
Bar
</div>
</div>
</div>
<div class="row rowThree">
<div class="a">
<div class="b">
Foobar
</div>
</div>
</div>
<button id="btn" class="btn" onclick="myFunction()">Button</button>
</div>
Thank you in advance.
Since they are all the same height (100% of the window height), the simple solution would be to simply scroll by that amount.
window.scrollBy(0, window.innerHeight);
Otherwise, you'll need to detect which element is the "current" one, and then get it's next sibling, and then scroll to it. Something like this (haven't tested, so syntax might be off, but this should give you an idea)
var winScroll = window.scrollTop; // current scroll of window
// find closest div
var rows = document.querySelectorAll('.row');
var closest = rows[0]; // first section
var closest_idx = 0;
var min = closest.offsetTop - winScroll;
rows.forEach(function(row, index) {
var divTopSpace = row.offsetTop - winScroll;
if( divTopSpave < min && divTopSpave > 0 ) {
closest = row;
closest_idx = index;
min = divTopSpace;
}
});
var next_idx = closest_idx + 1;
if (next_idx == rows.length) {
next_idx = 0;
}
window.scrollTo(rows[next_idx].scrollTop);

Increase and decrease value in Pure Javascript

I'm trying to develop a very simple carousel with Pure Javascript and CSS. I'm having trouble with the "next" and "previous" button, since they should communicate the with each other, setting the current position of the carousel.
Here is my current code (or JsFiddle: https://jsfiddle.net/kbumjLw2/1/):
// Slider
var listRecommendations = document.getElementById('list-recommendations');
listRecommendations.style.left = 0;
// Previous button
document.getElementById("btn-prev").onclick = function() {
// Making sure this functions will not run if it's the 0px of the slider
if (parseInt(listRecommendations.style.left) != 0) {
var currentPosition = parseInt(listRecommendations.style.left) + 100;
listRecommendations.style.left = currentPosition + 'px';
console.log(currentPosition);
};
}
// Next button
var num = 100;
var maxValue = 1000 + 120;
console.log(maxValue);
document.getElementById("btn-next").onclick = function() {
if (num < maxValue) {
num += 100;
listRecommendations.style.left = '-' + num + 'px';
console.log(num);
};
}
#list-recomendations{
position: absolute;
}
.wrap-items .item{
float: left;
}
<div class="recommendation">
<div id="slider">
<div id="list-recommendations" class="wrap-items">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
</div>
</div>
<!-- Slider controls -->
<button id="btn-prev" class="btn-slider prev">Previous</button>
<button id="btn-next" class="btn-slider next" title="Ver mais sugestões">Next</button>
</div>
As you can see on the console, the next button increases "100" at each click, and the previous button decreases "100" at each click. The previous button seems to be working fine, but the next button don't get the updated value, it always increase using the latest value it used.
Expected result:
Next button clicked: 100 > 200 > 300...
Prev button clicked: 200 > 100 > 0...
Next button clicked: 100 > 200 > 300...
Current result:
Next button clicked: 100 > 200 > 300...
Prev button clicked: 200 > 100 > 0...
Next button clicked: 400 > 500 > 600...
Any idea on what may be causing this issue?
check this updated fiddle
// Previous button
document.getElementById("btn-prev").onclick = function() {
// Making sure this functions will not run if it's the 0px of the slider
var currentPosition = parseInt(listRecommendations.style.left) - 100;
listRecommendations.style.left = currentPosition + 'px';
console.log(currentPosition);
}
// Next button
var num = 100;
var maxValue = 1000 + 120;
console.log(maxValue);
document.getElementById("btn-next").onclick = function() {
if (num < maxValue) {
var currentPosition = parseInt(listRecommendations.style.left) + 100;
num = currentPosition;
listRecommendations.style.left = num + 'px';
console.log(num);
};
}
you basically need to take the left value each time and do plus (+ next) minus (- prev) on it.
There is no use of num as you can play with the current position of the element.
Also note, - will concatenate the - symbol the the value, it will not subtract the value.
Ty this:
var maxValue = 1000 + 120;
var listRecommendations = document.getElementById('list-recommendations');
listRecommendations.style.left = 0;
document.getElementById("btn-prev").onclick = function() {
var val = parseInt(listRecommendations.style.left);
if (val != 0) {
val -= 100;
listRecommendations.style.left = val + 'px';
console.log(val);
};
}
document.getElementById("btn-next").onclick = function() {
var val = parseInt(listRecommendations.style.left);
if (val < maxValue) {
val += 100;
listRecommendations.style.left = val + 'px';
console.log(val);
};
}
#list-recomendations {
position: absolute;
}
.wrap-items .item {
float: left;
}
<div class="recommendation">
<div id="slider">
<div id="list-recommendations" class="wrap-items">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
</div>
</div>
<!-- Slider controls -->
<button id="btn-prev" class="btn-slider prev">Previous</button>
<button id="btn-next" class="btn-slider next" title="Ver mais sugestões">Next</button>
</div>
Fiddle here

Categories

Resources