Javascript scroll event simple animation - javascript

I want the square to be yellow with each scroll down, and the square to be green with each scroll up.
This snippet works almost the way I want it to, because what I want happens only when the square is no longer fully visible on the viewport.
I would like the scroll down to be yellow and the scroll up to be green.
const square = document.querySelector('.square');
const squarePos = square.getBoundingClientRect().top;
console.log(squarePos);
window.addEventListener('scroll',mouse=>{
const scrollTop = window.scrollY;
if (scrollTop >squarePos) {
square.style.background = "yellow";
}
else{
square.style.background = "green";
}
});
.square{
width:100px;
height:100px;
position:relative;
margin:0 auto;
background:red;
top:200px;
}
.content{
width:100vw;
height:150vh;
}
<div class = 'square'></div>
<div class = 'content'></div>

You need to compare your squarePos with the previous square pos, not the client y. Set the position with let, and update the value after each event listener callback.
const square = document.querySelector('.square');
let squarePos = square.getBoundingClientRect().top;
window.addEventListener('scroll', mouse => {
if (square.getBoundingClientRect().top > squarePos) {
square.style.background = "yellow";
}
else{
square.style.background = "green";
}
squarePos = square.getBoundingClientRect().top;
});
.square{
width:100px;
height:100px;
position:relative;
margin:0 auto;
background:red;
top:200px;
transition: background 200ms ease;
}
.content{
width:100vw;
height:150vh;
}
<div class = 'square'></div>
<div class = 'content'></div>

Maybe something like this?
The idea is get the previous scroll location (y) and compare to the current scroll location.
If the previous is bigger, then, it scroll up, otherwise scroll down
const square = document.querySelector('.square');
const squarePos = square.getBoundingClientRect().top;
let oldpos = 0;
window.addEventListener('scroll', mouse => {
const scrollTop = window.pageYOffset;
if (scrollTop > oldpos) {
square.style.background = "yellow";
} else {
square.style.background = "green";
}
oldpos = scrollTop
});
.square {
width: 100px;
height: 100px;
position: relative;
margin: 0 auto;
background: red;
top: 200px;
}
.content {
width: 100vw;
height: 150vh;
}
<div class='square'></div>
<div class='content'></div>

Related

Horizontal scroll loop in Cargo Collective

I'm trying to add an horizontal loop to my page but when I try to add the javascript cargo tells me that the script has been disabled. Why does that happen? Is there a way to implement that java without having problems? Is it right to add the javascript in the tag script at the end? This is where I've took the code from: https://codepen.io/lemmin/pen/bqNBpK
HTML:
<div id="page">
<div class="pane"><div>Looping Horizontal Scroll</div></div>
<div class="pane"><div>2</div></div>
<div class="pane"><div>3</div></div>
<div class="pane"><div>4</div></div>
<div class="pane"><div>5</div></div>
<div class="pane"><div>Last</div></div>
<div class="pane"><div>Looping Horizontal Scroll</div></div>
</div>
CSS:
body{
overflow-x:hidden;
color:#FFF;
font-family:Helvetica;
font-size:200%;
}
#page {
overflow:hidden;
white-space:nowrap;
position:fixed;
top:0;
left:0;
right:0;
bottom:0;
background-color:#CCC;
display:flex;
flex-wrap:no-wrap;
}
.pane {
flex:0 0 100vw;
height:100vh;
display:flex;
position:relative;
align-items:center;
justify-content:center;
background-color: #45CCFF;
}
.pane:nth-child(4n+2) {
background-color: #49E83E;
}
.pane:nth-child(4n+3) {
background-color: #EDDE05;
}
.pane:nth-child(4n+4) {
background-color: #E84B30;
}
.pane:last-child {
background-color: #45CCFF;
}
JS:
<script>
var page = document.getElementById('page');
var last_pane = page.getElementsByClassName('pane');
last_pane = last_pane[last_pane.length-1];
var dummy_x = null;
window.onscroll = function () {
var y = document.body.getBoundingClientRect().top;
page.scrollLeft = -y;
var diff = window.scrollY - dummy_x;
if (diff > 0) {
window.scrollTo(0, diff);
}
else if (window.scrollY == 0) {
window.scrollTo(0, dummy_x);
}
}
// Adjust the body height if the window resizes.
window.onresize = resize;
// Initial resize.
resize();
// Reset window-based vars
function resize() {
var w = page.scrollWidth-window.innerWidth+window.innerHeight;
document.body.style.height = w + 'px';
dummy_x = last_pane.getBoundingClientRect().left+window.scrollY;
}
</script>

Drag an element using JavaScript (Translating the position CSS3)

I am working on a small task, where I have to drag (translate) an element anywhere in the document freely. I have done the basic work but confused about the current position of the mouse. Because when I start dragging the element, the mouse position is not on the spot where the mousedown occurs.
Simply, I want the position of the mouse to stay on where I clicked on the box.
Here's the JSFiddle link.
Well you need to calculate the width and height of the element in order to keep the cursor in its center, note that now it's working with any width and height values, here i have added an animation just resizing width and height to see that always we get the center of the element
let target = document.querySelector(".drag");
function onDrag(e) {
// we could make them global variables instead
const {width, height} = window.getComputedStyle(target);
target.style.transform = `translate(${e.clientX - +width.replace("px", "") / 2}px, ${e.clientY - +height.replace("px", "") / 2}px)`;
}
function onLetGo() {
document.removeEventListener('mousemove', onDrag);
document.removeEventListener('mouseup', onLetGo);
}
function onGrab() {
document.addEventListener('mousemove', onDrag);
document.addEventListener('mouseup', onLetGo);
}
target.addEventListener('mousedown', onGrab);
* {
box-sizing: border-box;
}
.drag{
width: 100px;
height: 100px;
border: 1px solid black;
background: blue;
cursor: pointer;
position: fixed;
animation-name: resize;
animation-duration: 4s;
animation-timing-function: linear;
animation-iteration-count: infinite;
}
#keyframes resize {
0% {width: 100px}
25% {height: 150px}
50% {width: 150px}
100% {height: 100px}
}
<div class="drag"></div>
Edited to answer the comment of the OP
Thanks for the answer, it works fine. Is there any way, we can drag the div from any place where we click the div?
So now you want to drag the element from the clicked point and not from its center you can subtract event.offsetX from event.clientX to get the correct cursor position and the same for the y axis, and make sure there is no margin or padding for the containers, in this example I have removed the margin and padding from the HTML and BODY elements
let target = document.querySelector(".drag"), x = 0, y = 0;
function onDrag(e) {
// we use the coords of the mousedown event
target.style.transform = `translate(${e.clientX - x}px, ${e.clientY - y}px)`;
}
function onLetGo() {
document.removeEventListener('mousemove', onDrag);
document.removeEventListener('mouseup', onLetGo);
}
function onGrab(e) {
// we store the point of click(coords)
x = e.offsetX, y = e.offsetY;
document.addEventListener('mousemove', onDrag);
document.addEventListener('mouseup', onLetGo);
}
target.addEventListener('mousedown', onGrab);
* {
box-sizing: border-box;
}
html, body {
margin: 0;
padding: 0;
}
.drag{
width: 100px;
height: 100px;
border: 1px solid black;
background: blue;
cursor: pointer;
position: fixed;
}
<div class="drag"></div>
Well because transition is affected by margin, padding and other flow control rules you can avoid using it and just use the left and top rules to properly position your element like this
let target = document.querySelector(".drag"), x = 0, y = 0;
function onDrag(e) {
// use the `left` and `top` rules to properly position your element, so
// you no more care about other flow affecting rules
target.style.left = `${e.clientX - x}px`;
target.style.top = `${e.clientY - y}px`;
}
function onLetGo() {
document.removeEventListener('mousemove', onDrag);
document.removeEventListener('mouseup', onLetGo);
}
function onGrab(e) {
x = e.offsetX, y = e.offsetY;
document.addEventListener('mousemove', onDrag);
document.addEventListener('mouseup', onLetGo);
}
target.addEventListener('mousedown', onGrab);
.drag {
width: 100px;
height: 100px;
border: 1px solid black;
background: blue;
cursor: pointer;
position: fixed;
}
<div class="drag"></div>

Stick div at top not working properly : javascript

I going to create a scroll and stick div which has to stick on the top of the page but while scrolling down the div next to stickdiv automatically stick to the div before to sticky div
var left = document.getElementsByClassName("stickdiv");
for (var i = 0; i < left.length; i++) {
var stop = (left[0].offsetTop);
window.onscroll = function(e) {
var scrollTop = (window.pageYOffset !== undefined) ? window.pageYOffset : (document.documentElement || document.body.parentNode || document.body).scrollTop;
// left.offsetTop;
if (scrollTop >= stop) {
// get array item by index
left[0].classList.add('stick'); //adding a class name
} else {
// get array item by index
left[0].classList.remove('stick');
}
}
}
.stickdiv {
height: 50vh!important;
width: 100vh!important;
background-color: green!important;
}
.stick {
position: fixed;
top: 0;
margin: 0 0
}
#right {
float: right;
width: 100px;
height: 1000px;
background: red;
}
.des {
height: 300px;
width: 100%;
background-color: #000;
}
<div class="des"></div>
<div class="stickdiv"></div>
<div id="right"></div>
Example : green color div is the sticky div but after scrollingdown , red is also going to stick , I've tried position absolute in css but not working how to fix it
Here is the code to make green sticky when scrolling.
$ = document.querySelectorAll.bind(document);
// how far is the green div from the top of the page?
var initStickyTop = $(".stickdiv")[0].getBoundingClientRect().top + pageYOffset;
// clone the green div
var clone = $(".stickdiv")[0].cloneNode(true);
// hide it first
clone.style.display = "none";
// add it to dom
document.body.appendChild(clone);
addEventListener("scroll",stick=function() {
// if user scroll past the sticky div
if (initStickyTop < pageYOffset) {
// hide the green div but the div still take up the same space as before so scroll position is not changed
$(".stickdiv")[0].style.opacity = "0";
// make the clone sticky
clone.classList.add('stick');
// show the clone
clone.style.opacity="1";
clone.style.display = "block";
} else {
// make the clone not sticky anymore
clone.classList.remove("stick");
// hide it
clone.style.display = "none";
// show the green div
$(".stickdiv")[0].style.opacity="1";
};
});
// when resize, recalculate the position of the green div
addEventListener("resize", function() {
initStickyTop = $(".stickdiv")[0].getBoundingClientRect().top + pageYOffset;
stick();
});
.stickdiv {
height: 50vh!important;
width: 100vh!important;
background-color: green!important;
}
.stick {
position: fixed;
top: 0;
margin: 0 0
}
#right {
float: right;
width: 100px;
height: 1000px;
background: red;
}
.des {
height: 300px;
width: 100%;
background-color: #000;
}
<div class="des"></div>
<div class="stickdiv"></div>
<div id="right"></div>
JS FIDDLE
you might want to remove the stickdiv class and add it accordingly
if (scrollTop >= stop) {
// get array item by index
left[0].classList.add('stick'); //adding a class name
left[0].classList.remove('stickdiv');
} else {
// get array item by index
left[0].classList.remove('stick');
left[0].classList.add('stickdiv');
}

how to animate a div towards different direction and fade out using jquery

I am trying to build an animation effect where a div will float towards another div and when it reaches to the second div area, the floating div will fade out.Moving direction will be like this https://www.dropbox.com/s/2bpdbtycajuuk6a/1.JPG?dl=0 .For better understanding , i am providing my html and css code here.
html code....
<div id="outer_div">
<div class='a'>A</div>
<div class='b'>B</div>
<div class='c'>C</div>
<div class='d'>D</div>
</div>
and css ....
div.a {
width: 50px;
height:50px;
background-color:red;
position:absolute;
bottom:0;
top:450px;
left: 225px;
}
div.b {
width: 50px;
height:50px;
background-color:green;
position:absolute;
bottom:0;
top:225px;
left: 0px;
}
div.c {
width: 50px;
height:50px;
background-color:yellow;
position:absolute;
bottom:450px;
top:0px;
left: 225px;
}
div.d {
width: 50px;
height:50px;
background-color:pink;
position:absolute;
bottom:225px;
top:225px;
left: 450px;
}
#outer_div {
width: 500px;
height:500px;
background-color:blue;
position:fixed;
}
Here are 4 divs(A, B, C, D). A div will float where others are still. At first A div will float towards D and when touches D , A will fade out. Second, A div will float from the beginning towards C and when touches C , A will fade out. Third, A div will float from the beginning towards B and when touches B , A will fade out. Again the annimation will begin from the beginning and continue as before and this procedure will continue for 52 times.I have tried with this script but failed to do it .
Scripts ....
$(document).ready(function () {
animateDiv();
});
function makeNewPosition() {
// Get viewport dimensions (remove the dimension of the div)
var h = -$("#outer_div").height() - 50;
var w = -$("#outer_div").width()/2 - 50;
var nh = h;
var nw = w;
// var nh = Math.floor(Math.random() * h);
// var nw = Math.floor(Math.random() * w);
return [nh, nw];
}
function animateDiv() {
var newq = makeNewPosition();
var oldq = $('.a').offset();
var speed = calcSpeed([oldq.top, oldq.left], newq);
$('.a').animate({top: newq[0], right: newq[1]}, speed, function () {
animateDiv();
});
}
;
function calcSpeed(prev, next) {
var x = Math.abs(prev[1] - next[1]);
var y = Math.abs(prev[0] - next[0]);
var greatest = x > y ? x : y;
var speedModifier = 0.1;
var speed = Math.ceil(greatest / speedModifier);
return speed;
}
I couldn't understand the direction concept of the floating div A and how i am gonna detect that my floating div is at in the region of other div. Please help me with its solution and how can i understand animation direction concept in jquery(some reference can help a lot) ?
Try
$(document).ready(function () {
var a = $(".a")
, elems = $("#outer_div div").not(a)
, pos = function () {
return $.map(elems, function (el, i) {
return $(el).css(["left", "top"])
}).reverse()
}
, curr = 0
, max = 52
, speed = 1000;
(function animateDiv(el, p, curr, max) {
if (!!p.length) {
$(el)
.animate({
left:p[0].left
, top: (parseInt(p[0].top) + $(el).height())
}, speed, function () {
$(this).fadeOut(100, function () {
$(this)
.css({"top": "450px", "left":"225px"})
.fadeIn(0);
p.splice(0, 1);
animateDiv(this, p, curr, max)
})
})
} else if (curr < max) {
++curr;
console.log(curr, max);
animateDiv(el, pos(), curr, max)
}
}(a, pos(), curr, max))
});
div.a {
width: 50px;
height:50px;
background-color:red;
position:absolute;
bottom:0;
top:450px;
left: 225px;
}
div.b {
width: 50px;
height:50px;
background-color:green;
position:absolute;
bottom:0;
top:225px;
left: 0px;
}
div.c {
width: 50px;
height:50px;
background-color:yellow;
position:absolute;
bottom:450px;
top:0px;
left: 225px;
}
div.d {
width: 50px;
height:50px;
background-color:pink;
position:absolute;
bottom:225px;
top:225px;
left: 450px;
}
#outer_div {
width: 500px;
height:500px;
background-color:blue;
position:fixed;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="outer_div">
<div class='a'>A</div>
<div class='b'>B</div>
<div class='c'>C</div>
<div class='d'>D</div>
</div>
jsfiddle http://jsfiddle.net/83h17z25/2/

How to make this tooltip like this with pure javascript

I need to use JS no JQuery plugins to make a simple tooltip like on the image below.
Click on ? image should open this tooltip and click again on the same image to close it.
I think that it's simple for someone with good JS knowledge but I can't do it anyway :(
This is something that I have tried I know it's not too much but I am simply stuck.
How to display it like on the image, how to hide it when it's open and how to add that little triangle in the corner?
myfiddle
<img id="info" src="http://www.craiglotter.co.za/wp-content/uploads/2009/12/craig_question_mark_icon1.png"/>
<div id="ttip">bla bla</div>
document.getElementById('info').addEventListener('click', function(){
// how to check if it's visible so I can close tooltip
document.getElementById('ttip').style.display="block";
});
#info{margin-left:100px;margin-top:50px;}
#ttip
{
width: 280px;
z-index: 15001;
top: 0px;
left: 0px;
display: none;
border-color: #666;
background-color: #fff;
color: #666;
position: relative;
border: 1px solid #666;
padding: 15px 9px 5px 9px;
text-align: left;
word-wrap: break-word;
overflow: hidden;
}
Clean up the css and this will basically do it:
<script>
function doTip(e){
var elem = e.toElement;
if(elem.getAttribute('data-tip-on') === 'false') {
elem.setAttribute('data-tip-on', 'true');
var rect = elem.getBoundingClientRect();
var tipId = Math.random().toString(36).substring(7);
elem.setAttribute('data-tip-id', tipId);
var tip = document.createElement("div");
tip.setAttribute('id', tipId);
tip.innerHTML = elem.getAttribute('data-tip');
tip.style.top = rect.bottom+ 10 + 'px';
tip.style.left = (rect.left-200) + 'px';
tip.setAttribute('class','tip-box');
document.body.appendChild(tip);
} else {
elem.setAttribute('data-tip-on', 'false');
var tip = document.getElementById(elem.getAttribute('data-tip-id'));
tip.parentNode.removeChild(tip);
}
}
function enableTips(){
var elems = document.getElementsByClassName('quick-tip');
for(var i = 0; i < elems.length; i++) {
elems[0].addEventListener("click", doTip, false);
}
}
window.onload = function(){
enableTips();
}
</script>
<style>
.quick-tip {
background: black;
color: #fff;
padding: 5px;
cursor: pointer;
height: 15px;
width: 15px;
text-align: center;
font-weight: 900;
margin-left: 350px;
}
.tip-box {
/* change dimensions to be whatever the background image is */
height: 50px;
width: 200px;
background: grey;
border: 1px solid black;
position: absolute;
}
</style>
<div class="quick-tip" data-tip="THIS IS THE TIP! change elements 'data-tip' to change." data-tip-on="false">?</div>
<script>enableTips(); //might be required for jsfiddle, especially with reloads.</script>
Edit: fixed formatting and a bug. jsfiddle: http://jsfiddle.net/u93a3/
Proof of concept:
The following markup in HTML: Create a div with class tooltip, add image and a div with class info with all text (can be multiple paragraphs if needed, scollbars is shown if necessary):
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
</div>
</div>
The div.info is set to display:none in CSS.
When the page is loaded a pure javascript is running that draws an image of a triangle on a canvas-element, and then creates a div-element where the triangle is set as a background. Then, for every div.tooltip:
add a click-eventhandler to the image
replace the div.info with a div.info_container
add a clone of the triangle-div to div.info_container
add the original div.info to div.info_container
You can test it with this fiddle. It is tested successfully on FF25, Chrome31, IE10, Opera 12&18.
<!doctype html>
<html>
<head>
<script>
"use strict";
function click(event) {
var elem = this.parentNode.querySelector('div.info_container');
if (elem) elem.style.display = elem.style.display === 'block' ? 'none' : 'block';
}
function toolify() {
var idx,
len,
elem,
info,
text,
elements = document.querySelectorAll('div.tooltip'),
canvas,
imgurl,
pointer,
tipHeight = 20,
tipWidth = 20,
width = 200,
height = 100,
ctx;
// Create a canvas element where the triangle will be drawn
canvas = document.createElement('canvas');
canvas.width = tipHeight;
canvas.height = tipWidth;
ctx = canvas.getContext('2d');
ctx.strokeStyle = '#000'; // Border color
ctx.fillStyle = '#fff'; // background color
ctx.lineWidth = 1;
ctx.translate(-0.5,-0.5); // Move half pixel to make sharp lines
ctx.beginPath();
ctx.moveTo(1,canvas.height); // lower left corner
ctx.lineTo(canvas.width, 1); // upper right corner
ctx.lineTo(canvas.width,canvas.height); // lower right corner
ctx.fill(); // fill the background
ctx.stroke(); // stroke it with border
//fix bottom row
ctx.fillRect(0,canvas.height-0.5,canvas.width-1,canvas.height+2);
// Create a div element where the triangel will be set as background
pointer = document.createElement('div');
pointer.style.width = canvas.width + 'px';
pointer.style.height = canvas.height + 'px';
pointer.innerHTML = ' ' // non breaking space
pointer.style.backgroundImage = 'url(' + canvas.toDataURL() + ')';
pointer.style.position = 'absolute';
pointer.style.top = '2px';
pointer.style.right = '1px';
pointer.style.zIndex = '1'; // place it over the other elements
for (idx=0, len=elements.length; idx < len; ++idx) {
elem = elements[idx];
elem.querySelector('img').addEventListener('click',click);
text = elem.querySelector('div.info');
// Create a new div element, and place the text and pointer in it
info = document.createElement('div');
text.parentNode.replaceChild(info,text);
info.className = 'info_container';
info.appendChild(pointer.cloneNode());
info.appendChild(text);
//info.addEventListener('click',click);
}
}
window.addEventListener('load',toolify);
</script>
<style>
div.tooltip
{
position:relative;
display:inline-block;
width:300px;
text-align:right;
}
div.tooltip > div.info
{
display:none;
}
div.tooltip div.info_container
{
position:absolute;
right:20px;
width:200px;
height:100px;
display:none;
}
div.tooltip div.info
{
text-align:left;
position:absolute;
left:1px;
right:1px;
top:20px;
bottom:1px;
color:#000;
padding:5px;
overflow:auto;
border:1px solid #000;
}
</style>
</head>
<body>
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
</div>
</div>
<div class='tooltip'>
<img src='craig_question_mark_icon1.png' alt='Help'/>
<div class='info'>
Some text to fill the box with.
Some text to fill the box with.
Some text to fill the box with.
Some text to fill the box with.
</div>
</div>
</body>
</html>

Categories