Show/hide div in viewport after 2 seconds - javascript

I want show when its in viewport after 2 seconds. And if its not in viewport just hide.
I watched a code, but its relative to other div and without delay.
Thx!
$(window).scroll(function() {
if ($('.waar').is(':in-viewport')) {
$('.sticky-info').hide();
} else {
$('.sticky-info').show();
}
});

You can refer this link - slideToggle w3school
slideToggle jquery api
Definition and Usage
The slideToggle() method toggles between slideUp() and slideDown() for the selected elements.
This method checks the selected elements for visibility. slideDown() is run if an element is hidden. slideUp() is run if an element is visible - This creates a toggle effect.
Syntax
$(selector).slideToggle(speed,easing,callback)
1. $(Your selectior).slideToggle("fast"); // fast
2. $(Your selectior).slideToggle("medium"); // meduim
3. $(Your selectior).slideToggle("slow"); // slow
Another example you can use this also
Please refer this link - > fadeToggle
$(function() {
$('#ButtonClick').on('click', function() {
$('#HideShowDiv').delay(1000).fadeToggle();
});
});

The below SO snippet might help!
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>Document</title>
<style>
#container {
height: 1000px;
position: relative;
margin-top: 40px;
}
#inner {
width: 50%;
color: white;
margin: auto;
height: 50px;
background-color: green;
}
#sticky-info {
top: 0;
position: fixed;
z-index: 1;
display: block;
background-color: hotpink;
}
</style>
</head>
<body>
<div id="container">
<div id="inner">
Scroll me out of viewport
</div>
<div id="sticky-info">
Element in view
</div>
</div>
<script>
let inView = true;
let timeout = null;
window.addEventListener("scroll", () => {
const bounding = document
.getElementById("inner")
.getBoundingClientRect();
if (
bounding.top >= 0 &&
bounding.left >= 0 &&
bounding.right <= window.innerWidth &&
bounding.bottom <= window.innerHeight
) {
if (!inView) {
inView = true;
clearTimeout(timeout);
timeout = setTimeout(() => {
document.getElementById("sticky-info").style.display = "block";
}, 2000);
}
} else {
if (inView) {
clearTimeout(timeout);
inView = false;
timeout = setTimeout(() => {
document.getElementById("sticky-info").style.display = "none";
}, 2000);
}
}
});
</script>
</body>
</html>

Related

Why the transform translate is not working?

I am using this code to simply move a small element(ball here), but the transform translate is only working once, even when the setInterval() function is continuously working?
This is the html file --
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="MoveTheBall.css">
<title>Move the ball</title>
</head>
<body>
<div class="ball"></div>
<script src="MoveTheBall.js"></script>
</body>
</html>
and CSS file--
.ball{
height: 5rem;
width: 5rem;
background-color: salmon;
border-radius: 50%;
position: relative;
top: 35vw;
left: 45vw;
}
and the JavaScript file--
var ball = document.querySelector('.ball');
document.addEventListener('keypress' , function(event) {
console.log('key', event.key);
if(event.key === 'w') {
moveUp();
}
});
function moveUp() {
let ballRect;
let interval = setInterval(function() {
ballRect = ball.getBoundingClientRect();
if(ballRect.top > 0) {
ball.style.transform = 'translateY(-10px)';
} else {
clearInterval(interval);
}
}, 300);
}
Here I was expecting to move the ball up until it reaches to the top of the screen after pressing w key. But the ball is only moving only once.
function moveUp() {
let ballRect;
let interval = setInterval(function() {
ballRect = ball.getBoundingClientRect();
if(ballRect.top > 0) {
let currentTop = parseFloat(getComputedStyle(ball).getPropertyValue('top'));
ball.style.transform = `translateY(${currentTop - 10}px)`;
} else {
clearInterval(interval);
}
}, 300);
}

Inverted logo based on background colour

I'm wondering if anyone has discovered a beautiful way to rotate out logo's based on 'sections' of the page.
In more detail I have a logo on a transparent navbar, let's say a white logo.
My page is broken into sections, some gray/light background some darker/black backgrounds. As I scroll, I hope that the sticky logo will be swapped out to an opposing color. I attempted to do this by naming each section with an id such as id='white and id=black.
Then once I scrolled down and hit that I'd trigger the function and swap out the picture, although, I realized that it only detects the first id of white or the second of black.
Not sure how to approach this other then make a unique id for each section, which, seems barbaric.
window.onscroll = function() {
myFunction()
};
function myFunction() {
if ($(this).scrollTop() >= $('#white').position().top) {
logoSwap(0);
} else if (($(this).scrollTop() >= $('#black').position().top)) {
logoSwap(1);
}
}
function logoSwap(which) {
if (which) {
$('#logo').css("background-color", "black");
} else {
$('#logo').css("background-color", "white");
}
}
#logo {
position: fixed;
top: 0;
left: 0;
height: 50px;
width: 50px;
background-color: black;
}
.h500 {
height: 500px;
}
.white {
background-color: white;
}
.black {
background-color: black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="logo">
</div>
<section id="white" class='h500 white'>
</section>
<section id="black" class='h500 black'>
</section>
<section id="white" class='h500 white'>
</section>
<section id="black" class='h500 black'>
</section>
You have to use classes and not id's because there must be only one item in the document having a same id, contrary to class.
About the script: the idea is to iterate over all the sections .white or .black and get the top and bottom for each one, which will allow you while handling scrolling event to verify if your logo is inside a given section (between the section's top and bottom positions)
Edit: I add this code (with pure javascript) to my comment.
const whites = [...document.querySelectorAll('.white')].map(e => ({
top: e.getBoundingClientRect().top,
bottom: e.getBoundingClientRect().bottom
}));
//If you have a logic of only white and black sections, you can omit blacks, else you can use them
// const blacks = [...document.querySelectorAll('.black')].map(e => ({top: e.top, bottom: e.bottom}));
const logo = document.querySelector('#logo');
document.addEventListener('scroll', () => {
let position = (logo.getBoundingClientRect().bottom + logo.getBoundingClientRect().top) / 2 + window.scrollY;
for (let i = 0; i < whites.length; i++) {
if (position >= whites[i].top && position <= whites[i].bottom) {
logo.classList.remove('whiteLogo');
logo.classList.add('blackLogo');
return;
}
}
logo.classList.remove('blackLogo');
logo.classList.add('whiteLogo');
});
*,
html,
body {
margin: 0;
padding: 0;
}
section {
height: 200px;
}
.black,
.blackLogo {
background: black;
}
.white,
.whiteLogo {
background: white;
}
#logo {
position: fixed;
top: 0;
left: 0;
height: 50px;
width: 50px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="logo" class="whiteLogo"></div>
<section class="black"></section>
<section class="white"></section>
<section class="black"></section>
<section class="black"></section>
<section class="white"></section>
<section class="black"></section>
</body>
</html>
DOM id's need to be unique, so your code will only recognize the first instance of each. You should find the last section you scrolled over, and find what class that has:
function myFunction() {
var position = $(this).scrollTop()
var class_pos = $('.white, .black').filter(function(){ return position >= $(this).position().top})
// console.log(class_pos)
if ($(class_pos[class_pos.length - 1]).hasClass('white')){
logoSwap(0);
} else {
logoSwap(1);
}
}

How to implement resizable div with fixed increments in Javascript?

I want to implement a vertical resizable div such that it increases height in certain fixed intervals. I don't want to use any libraries and looking for plain JS implementation. Here is jquery version: https://jqueryui.com/resizable/#snap-to-grid
This code works good but increases height by one pixel on each mousemove (vertically).
When I try to increase height by 10, the height increases but the mouse pointer does not stick to the base of div..,
https://plnkr.co/edit/3VesixHE2B7N46f8N7Bg?p=preview
const divElement = document.querySelector('.ns-resize');
const element = document.querySelector('.resizable');
let original_height = parseFloat(getComputedStyle(element, null).getPropertyValue('height').replace('px', ''));
let original_Y = element.getBoundingClientRect().top;
divElement.onmousedown = function(mouseDownEvent) {
mouseDownEvent.preventDefault();
var original_mouse_y = mouseDownEvent.pageY;
document.addEventListener('mousemove', resize);
document.addEventListener('mouseup', stopResize);
function resize(mouseUpEvent) {
//cmp.increment = cmp.increment + 15;
const height = original_height + (mouseUpEvent.pageY - original_mouse_y);
if (height > 15 && height < 900) {
mouseUpEvent.pageY = mouseUpEvent.pageY ;
element.style.height = height + 'px';
divElement.innerHTML = element.style.height;
}
}
function stopResize() {
document.removeEventListener('mousemove', resize)
}
}
/* Styles go here */
.resizable {
width: 100px;
height : 100px;
border:1px solid red;
position: absolute;
}
.container {
position : relative;
}
.ns-resize {
position: absolute;
bottom: 0px;
cursor: ns-resize;
width: 100%;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="resizable">
<div class="ns-resize">
<span> </span>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
}
I could increase height by one pixel on every mousemove event, but what I really want is to increase by 10px each time.
As indicated in my comment, CSS already has a resize property you can use to make an element resizable. The only thing you need to do after a resize, is round the current height to the nearest 10px.
document.querySelector( '.resizable' ).addEventListener( 'mouseup', event => {
const current_height = parseInt( event.target.style.height, 10 );
event.target.style.height = Math.round( current_height / 10 ) * 10 + 'px';
console.log( `changed height from ${ current_height }px to ${ event.target.style.height }` );
});
.resizable {
border: 1px solid red;
height: 100px;
overflow: hidden;
resize: vertical;
width: 100px;
}
<div class="resizable"></div>
Only mighty want to add a check now to not run the function when something else inside the div is clicked.

How to create smooth and goodlooking slightly text?

I want to create a text that can be shifted for long title.
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style>
#abc {
position: relative;
overflow: hidden;
width: 200px;
height: 100px;
}
#def {
position: absolute;
font-size: 2em;
color: #000;
margin: 0;
width: 400px;
}
</style>
<script>
var teks = null;
function geser() {
var left = 0;
function frame() {
left--; // update parameter
teks.style.left = left + 'px';
if (left == -200) {
clearInterval(id);
setTimeout(function() {
runningtext();
}, 2000);
}
}
var id = setInterval(frame, 40)
}
function runningtext() {
teks = document.getElementById("def");
teks.style.left = '0px';
setTimeout(function() {
geser();
}, 2000);
}
window.onload = runningtext;
</script>
</head>
<body>
<div id="abc">
<p id="def">Cihampelas Demin Center</p>
</div>
</body>
</html>
The script is successfully work with 1 line.
Output :
Cihampelas Demin Center
Question is :
Is there another way to print 1 line without #def { width:400px; }?
(When I try #def { display:inline; }
Output :
Cihampelas
Demin Center
)
When object's left = -200px, I want to reserve in same way, but I have no idea.

jsfiddle code not working on my site

HTML:
<div id="container">
<div id="bar">
</div>
</div>
CSS:
#container {
width: 20px;
height: 150px;
position: relative;
}
#bar {
width: 100%;
height: 100%;
background-color: red;
position: absolute;
bottom: 0px;
}
JS:
function Bar(element) {
this.barEl = element;
this.progress = 100;
}
Bar.prototype.setProgress = function (p) {
if(p >= 0) {
this.progress = p;
this.barEl.style.height = this.progress + "%";
}
}
var barObj = new Bar(document.getElementById('bar'));
setInterval(function () {
barObj.setProgress(barObj.progress - 10);
}, 1000);
This code from jsfiddle http://jsfiddle.net/Mp7R3/ is not working when I copy paste the code but it is working fine on jsfiddle .maybe I have some onLoad problem but I dont know how to solve it . I tried $(document).ready(function() but it didnt help .
Be sure you don't forget the script for calling jQuery in the <head> of your code:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
You can also try to place the code at the bottom of your code so it's can run only if the full page is loaded.
I also write below the simplest page to make this code work (normally you should separate HTML, CSS and JS), so you can compare it with your own:
<!DOCTYPE html>
<html>
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<title>- That's Work!!! -</title>
<style>
#container {
width: 20px;
height: 150px;
position: relative;
}
#bar {
width: 100%;
height: 100%;
background-color: red;
position: absolute;
bottom: 0px;
}
</style>
</head>
<body>
<div id="container">
<div id="bar">
</div>
</div>
</body>
<script type="text/javascript">
function Bar(element) {
this.barEl = element;
this.progress = 100;
}
Bar.prototype.setProgress = function (p) {
if(p >= 0) {
this.progress = p;
this.barEl.style.height = this.progress + "%";
}
}
var barObj = new Bar(document.getElementById('bar'));
setInterval(function () {
barObj.setProgress(barObj.progress - 10);
}, 1000);
</script>
</html>
I hope it will help you!

Categories

Resources