can you please tell me how to move header up and down after reqular interval of time .It mean I need to show red header for 3 sec and then green header for 3 second.I Think it will use slide up and slide down event of jquery and and change the top position of div.
http://jsfiddle.net/HL5h5/
.redrect{
position: relative;
top:0px;
width:100%;
background-color:red;
height:100px
}
.greenrect{
position:relative;
top:200px
width:100%;
background-color:green;
height:100px
}
If you want to have both visible at all times:
Fiddle
HTML:
<div class ="redrect"> </div>
<div class ="greenrect"> </div>
CSS:
.redrect{
position : relative;
background: #c00;
height : 100px
}
.greenrect {
position : relative;
background: #0a0;
height : 100px
}
JS:
function flip() {
var x = parseInt($(".redrect").css('top')) ? 0 : 100,
z = x ? [20, 10] : [10, 20];
$(".redrect").animate({top: x, zIndex: z[0]}, 450);
$(".greenrect").animate({top: -x, zIndex: z[1]}, 450);
}
setInterval(flip, 3000);
Edit:
Top down slide thing:
Fiddle
HTML:
Lorem ipsum
<div id="wrap">
<div class ="redrect">Eloha </div>
<div class ="greenrect">Hi </div>
</div>
<button id="toggle">Stop</button>
CSS:
#wrap {
height : 100px;
overflow : hidden;
position : relative;
}
.redrect{
position : absolute;
background: #c00;
height : 100px;
width : 100%;
}
.greenrect {
position : absolute;
background: #0a0;
height : 100px;
width : 100%;
top : -100px;
}
JS:
function flipper(a, b, tw, ta) {
this.a = a; // Element 1
this.b = b; // Element 2
this.t_anim = ta || 750; // Animation time
this.t_wait = tw || 3000; // Interval time
this.tt = null;
// Flip the two elements
var flip = function($a, $b, time) {
$a.css('zIndex', 10);
$b.css('zIndex', 20).animate({
top : 0
}, time).
promise().done(function() {
$a.css('top', -100);
});
};
// Tick triggered by interval
this.tick = function() {
if (parseInt($(this.a).css('top'), 10))
flip($(this.b), $(this.a), this.t_anim);
else
flip($(this.a), $(this.b), this.t_anim);
return this;
};
// Toggle run/stop
this.toggle = function() {
if (this.tt !== null)
this.stop();
else
this.start();
return this.tt !== null;
};
// Stop
this.stop = function() {
clearInterval(this.tt);
this.tt = null;
return this;
};
// Start
this.start = function() {
this.stop(); // Make sure to stop it.
this.tt = setInterval(
$.proxy(this.tick, this),
this.t_wait
);
return this;
};
return this;
}
var ff = new flipper(
".redrect",
".greenrect",
1500, // Interval time
750 // Animation time
)
.start();
$("#toggle").on("click", function(e){
$(this).html(ff.toggle() ? "Stop" : "Start");
});
Try This:
CSS:
.redrect {
position: relative;
top:0px;
width:100%;
background-color:red;
height:100px
}
.greenrect {
display:none;
position:relative;
top:200px width:100%;
background-color:green;
height:100px;
}
JS:
$(function () {
setInterval(function () {
$(".redrect").slideToggle();
$(".greenrect").slideToggle();
}, 3000);
});
jsFiddle
Related
I am working on my portfolio website and I am a complete beginner in Javascript.
I would like a button which has its position fixed, to slowly fade in when I scroll down (suppose when I scroll to >=20px from the top of the document, it should fade in) and when I scroll back up to the original position, it should gradually fade out.
I have already tried my hand and written a code for this. It is working perfectly when you scroll down and up. But when you quickly scroll and stop scrolling in the mid-way, it behaves pretty abnormally (suddenly appears or disappears).
HTML:
<div class="a_large_page">
<div class="enclose bordar black" id="bottomtoup">hello</div>
</div>
JS:
mybutton = document.getElementById("bottomtoup")
// initially, the button stays hidden
visible = false
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {
if (!visible) { // if the button is not visible,
unfade(mybutton); // function to gradually fadein button
visible = true; // button is visible so, set visible = false to true.
}
} else {
if (visible) { // if the button is visible,
fade(mybutton); // function to gradually fadeout button
visible = false; // set visible = true back to false
}
}
}
function unfade(element) {
var op = 0.1; // initial opacity
element.style.display = 'flex';
var timer = setInterval(function() {
if (op >= 1) {
clearInterval(timer);
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op += op * 0.1;
}, 10);
}
function fade(element) {
var op = 1; // initial opacity
var timer = setInterval(function() {
if (op <= 0.1) {
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
Here is the fiddle: https://jsfiddle.net/P0intMaN/Lmp6u5ft/23/
My code is pretty substandard for sure. That's why it is behaving in this way. Hence, I am looking for an efficient way to achieve this. I have seen people making use of JQuery to do this, but I don't know JQuery at all. So, it would be much appreciated if the code is in pure JS.
I've changed your code and removed setInterval usage. This can be solved with it but may be harder to understand for newer coders.
There are also flags to keep track of whether you are currently fading or unfading to ensure you do not stack or "overlap" timeout/intervals.
mybutton = document.getElementById("bottomtoup")
// initially, the button stays hidden
var visible = false
// When the user scrolls down 20px from the top of the document, show the button
window.onscroll = function() {
scrollFunction()
};
function scrollFunction() {
var threshold = 20;
var below_threshold = document.body.scrollTop > threshold || document.documentElement.scrollTop > threshold;
if (below_threshold) {
if (!visible) { // if the button is not visible,
unfade(mybutton); // function to gradually fadein button
}
return;
}
if (visible) { // if the button is visible,
fade(mybutton); // function to gradually fadeout button
}
}
var current_opacity = 0.1;
var is_unfading = false;
var is_fading = false;
function unfade(element) {
if(!visible){
element.style.display = 'flex';
visible = true;
}
is_fading = false;
is_unfading = true;
unfade_step(element);
}
function unfade_step(element){
element.style.opacity = current_opacity;
element.style.filter = 'alpha(opacity=' + current_opacity * 100 + ")";
if (current_opacity >= 1){
// end
is_unfading = false;
current_opacity = 1;
return;
}
current_opacity += 0.01;
if(is_unfading){
setTimeout(function(){
unfade_step(element);
}, 10);
}
}
function fade(element) {
if(!visible){
return;
}
is_fading = true;
is_unfading = false;
fade_step(element);
}
function fade_step(element) {
element.style.opacity = current_opacity;
element.style.filter = 'alpha(opacity=' + current_opacity * 100 + ")";
if (current_opacity <= 0.001){
// end
is_fading = false;
visible = false;
current_opacity = 0.1;
element.style.display = 'none';
return;
}
current_opacity -= 0.01;
if(is_fading){
setTimeout(function(){
fade_step(element);
}, 10);
}
}
There is no need to have so much JS when you can do in so little:
If you feel to change the timing of
// Set a function onscroll - this will activate if the user scrolls
window.onscroll = function() {
// Set the height to check for
var appear = 20
if (window.pageYOffset >= appear) {
// If more show the element
document.getElementById("bottomtop").style.opacity = '1'
document.getElementById("bottomtop").style.pointerEvents = 'all'
} else {
// Else hide it
document.getElementById("bottomtop").style.opacity = '0'
document.getElementById("bottomtop").style.pointerEvents = 'none'
}
}
.a_large_page{
background-color: gray;
height: 2000px;
}
.enclose{
height: 40px;
width: 40px;
position:fixed;
margin-right: 20px;
margin-bottom: 20px;
right:0;
bottom:0;
pointer-events:none;
opacity:0;
justify-content: center;
align-items: center;
color:white;
/* This determines how fast animation takes place, you can change it as per your choice. */
transition:all 0.6s;
}
.enclose:hover{
cursor: pointer;
}
<div class="a_large_page">
<div class="enclose bordar black" id="bottomtop">hello</div>
</div>
There is no need to sense the scroll event in more modern browsers as you can use IntersetionObserver to tell you when scrolling has gone past 20px;
You can do this by placing a tiny element at the top of the page with height 20px. You then ask the system to tell you when this has gone out of, or comes back into, the viewport. At these points you can set the opacity of the Hello to 1 or 0 as appropriate.
The extra bonus is that you get rid of a lot of code and there isn't the possible clash between set intervals as we use transition on the opacity to do the gradual fade in/out.
// See MDN for more info on IntersectioObserver
let callback = (entries, observer) => {
entries.forEach(entry => {
if (entry.isIntersecting) {
mybutton.style.opacity = 0;
} else {
mybutton.style.opacity = 1;
}
});
};
const mybutton = document.getElementById("bottomtoup")
const observer = new IntersectionObserver(callback);
const observed = document.getElementById("observed");
observer.observe(observed);
.a_large_page {
background-color: gray;
height: 2000px;
position: relative;
}
#observed {
position: absolute;
top: 0;
left: 0;
height: 20px;
width: 10px;
z-index: -999;
}
.enclose {
height: 40px;
width: 40px;
position: fixed;
margin-right: 20px;
margin-bottom: 20px;
right: 0;
bottom: 0;
justify-content: center;
align-items: center;
color: white;
opacity: 0;
transition: opacity 1s linear;
}
<div class="a_large_page">
<div id="observed"></div>
<div class="enclose bordar black" id="bottomtoup">hello</div>
</div>
Here is some Javascript and CSS from my program:
<script>
var $body = $('body');
$body.waypoint(function (direction) {
if (direction == 'down') {
$body.addClass('body2');
} else{
$body.removeClass('body2');
}
}, { offset: '50%'});
</script>
<style>
body {
background-image: url("images/image1.png");
background-repeat: no-repeat;
background-position: 400px 200px;
background-size: 900px 300px;
margin-right: 400px;
background-attachment: fixed;
}
.body2 {
background-image: url("images/image2.png");
background-repeat: no-repeat;
background-position: 400px 200px;
background-size: 900px 300px;
margin-right: 400px;
background-attachment: fixed;
}
I'm trying to change the background image from image1 (body) to image2 (body2) as I scroll 50% of the way down the page. However, when I launch the program the only image displayed is image2 and nothing changes as I scroll. Any help would be greatly appreciated, thanks in advance!
I tried to use waypoints, but I can't seem to make it work though (it gives unreliable results for me, on Chrome).
You could use your own custom function to handle the scroll event as you wish.
You need to compute:
height: total document height (offset 50% = height/2)
y: current scroll position
direction: by comparing y with the last scroll position
Like in this example (Run code snippet):
/**
* very simple on scroll event handler
* use: Scroller.onScroll(..custom function here...)
* custom function gets 3 parameters: y, height and direction
*/
var Scroller = {
_initiated: 0,
_init: function() {
var t = this;
t._listener = function() {
t._scrollEvent();
};
window.addEventListener("scroll", t._listener);
t.y = t.getY();
t._initiated = 1;
},
_onScroll: null,
_scrollEvent: function() {
var t = this;
if (!t._initiated || !t._onScroll)
return false;
var y = t.getY();
t.height = document.body.scrollHeight;
t.direction = y < t.y ? "up" : "down";
t.y = y;
t._onScroll(t.y, t.height, t.direction);
},
getY: function() {
//for cross-browser compatability
// https://stackoverflow.com/a/51933072/4902724
return (window.pageYOffset !== undefined) ?
window.pageYOffset :
(document.documentElement || document.body.parentNode || document.body).scrollTop;
},
onScroll: function(fn) {
var t = this;
t._onScroll = fn;
if (!t._initiated)
t._init();
},
destroy: function() {
var t = this;
window.removeEventListener("scroll", t._listener);
t._onScroll = null;
t._initiated = 0;
}
};
/**
* global vars
*/
var $body = $("body");
// keep track of changes, to cancel unnecessary class changes
$body.classChanged = 0;
/**
* on scroll setup
*/
Scroller.onScroll(function(y, height, direction) {
/* to check for 50%, compare y vs. height/2 */
if (y > height / 2 && direction == "down" && !$body.classChanged) {
$body.addClass("body2");
$body.classChanged = 1;
}
if (y < height / 2 && direction == "up" && $body.classChanged) {
$body.removeClass("body2");
$body.classChanged = 0;
}
});
body {
background-color: lightgreen;
}
.body2 {
background-color: gold;
}
/* demo helpers...*/
div {
float: left;
width: 100%;
height: 250px;
border: 1px solid grey;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p>Sroll down below 50% to change body color...."</p>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
Hope this helps, even without that plugin.
I've actually figured out the problem. All I needed to do was set the offset percentage as negative.
Have a java script table that connects to a web socket and update table.
I want to use jquery falsher to flash if the value is greater than and less than the current value.
Update Table function
var child = createStockNode(stock, type, template);
// try to replace
var stockNode = document.querySelector(type + "[data-symbol=" + stock.n + "]");
if (stockNode) {
table.replaceChild(child, stockNode);
} else {
// add new stock
table.appendChild(child);
}
//stock.c ===> close Price
var bg = stock.c < 0
? '255,148,148' // red
: '154,240,117'; // green
$row = child;
$row.flash(bg, 1000);
//child.flash(bg , 1000)
}
Jquery flusher function
jQuery.fn.flash = function (color, duration) {
var current = this.css('backgroundColor');
this.animate({ backgroundColor: 'rgb(' + color + ')' }, duration / 2)
.animate({ backgroundColor: current }, duration / 2);
};
Error Uncaught ReferenceError: $row is not defined
Jquery is defined in my html page as well.
EDIT
The jQuery documentation about the animate() function specifies :
For example, width, height, or left can be animated but background-color cannot be, unless the jQuery.Color plugin is used
I'd recommand to use CSS3 for thins kind of animation.
Still, here are to ways of flashing.
(function($) {
$.fn.blink = function(options) {
var defaults = {
delay: 500
};
var options = $.extend(defaults, options);
return this.each(function() {
var obj = $(this);
var blink = false;
setInterval(function() {
if (blink) {
$(obj).css('background', options.from);
} else {
$(obj).css('background', options.to);
}
blink = !blink;
}, options.delay);
});
}
}(jQuery))
$('#purejQuery').blink({
delay: 500,
from: "red",
to: "blue"
});
/* The animation code */
#keyframes blinking {
0%{
background-color: red;
}
50%{
background-color: red;
}
51%{
background-color: blue;
}
100%{
background-color: blue;
}
}
#pureCSS {
width: 100px;
height: 100px;
animation: blinking 1s infinite;
}
#purejQuery {
width: 100px;
height: 100px;
background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="pureCSS">Done by CSS</div>
<div id="purejQuery">Done by jQuery</div>
I have tried to create single scroll and move to next section, I have using javascript, It is not working fine, The window top distance not giving properly, I need to div fullscreen moved to next screen, Please without jquery, Please help
if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);
window.onmousewheel = document.onmousewheel = wheel;}
function wheel(event) {
var delta = 0;
if (event.wheelDelta) delta = (event.wheelDelta)/120 ;
else if (event.detail) delta = -(event.detail)/3;
handle(delta);
if (event.preventDefault) event.preventDefault();
event.returnValue = false;
}
function handle(sentido) {
var inicial = document.body.scrollTop;
var time = 500;
var distance = 900;
animate({
delay: 0,
duration: time,
delta: function(p) {return p;},
step: function(delta) {
window.scrollTo(0, inicial-distance*delta*sentido);
}
});
}
function animate(opts) {
var start = new Date();
var id = setInterval(function() {
var timePassed = new Date() - start;
var progress = (timePassed / opts.duration);
if (progress > 1) {progress = 1;}
var delta = opts.delta(progress);
opts.step(delta);
if (progress == 1) {clearInterval(id);}}, opts.delay || 10);
}
body{
width: 100%;
height: 100%;
margin:0;
padding:0;
}
.wrapper{
width: 100%;
height: 100%;
position: absolute;
}
section{
width: 100%;
height: 100%;
}
.pg1{
background: green;
}
.pg2{
background: blue;
}
.pg3{
background: yellow;
}
<div class="wrapper" id="myDiv">
<section class="pg1" id="sec1"></section>
<section class="pg2"></section>
<section class="pg3"></section>
</div>
Return the height of the element and store it in distance variable, instead of giving it a static 900.
From this:
var distance = 900;
To this:
var distance = document.getElementById('sec1').clientHeight;
Hi i'm building a javascript slider for my portfolio with Javascript. The slides work properly but when i add a fading transition i keep getting a white flash between the 2 slides. Anyone knows how to create a smooth fade between them?
Here's my working fiddle: https://jsfiddle.net/t9ezr8wr/2/
My javascript:
$(function () {
var theInterval; // Slide speed
var images = new Array();
var counter = 1;
var defaultSettings = {
"sliderContainer": "#slider" // SliderContainer
, "pauseWithMouse": true // Turn on/off pause with mouse
, "sliderSpeed": 3000 // Slide speed
, "transitionSpeed": 200 // transition speed
};
// intialize slider
// if myImages exists then
images = myImages;
if (images.length > 0) {
$(defaultSettings.sliderContainer).append('<img id="sliderImg" width="900" src="' + images[0] + '" />');
startSlide(images);
}
function cycleImages(images) {
if (counter >= images.length) {
counter = 0;
}
console.log(counter);
document.getElementById("sliderImg").src = images[counter];
counter++;
var images = $('#sliderImg')
var now = images.filter(':visible')
var next = now.next().length ? now.next() : images.first()
var speed = defaultSettings.transitionSpeed; //Transition speed
now.fadeOut(speed);
next.fadeIn(speed);
}
function startSlide() {
console.log('start');
theInterval = setInterval(function () {
cycleImages(images);
}, defaultSettings.sliderSpeed);
// Set interval time
};
var stopSlide = function () { // Stop slides on hover
console.log('stop');
if (defaultSettings.pauseWithMouse) {
clearInterval(theInterval);
}
};
$('#sliderImg').on('mouseover', function () { // Stop slides on mouseover
stopSlide();
});
$('#sliderImg').on('mouseout', function () { // Continue with slides on mouseout
startSlide();
});
});
what u wanted couldn't be achieved with one image ,so i used two image to achieve the desired effect.
JS:
$(function () {
var theInterval; // Slide speed
var images = new Array();
var counter = 1;
var defaultSettings = {
"sliderContainer": "#slider" // SliderContainer
, "pauseWithMouse": true // Turn on/off pause with mouse
, "sliderSpeed": 3000 // Slide speed
, "transitionSpeed": 600 // transition speed
};
// intialize slider
// if myImages exists then
images = myImages;
if (images.length > 0) {
$(defaultSettings.sliderContainer).append('<img id="sliderImg" width="900" style="display:block" src="' + images[0] + '" />');
$(defaultSettings.sliderContainer).append('<img id="sliderImg2" width="900" style="display:none" src="' + images[1] + '" />');
startSlide(images);
}
function cycleImages(images) {
if (counter >= images.length) {
counter = 0;
}
console.log(counter);
document.getElementById("sliderImg").src = images[counter];
counter++;
document.getElementById("sliderImg2").src = images[counter >= images.length ? 0 : counter];
var images = $('#sliderImg')
var now = $("#sliderImg")
var next = $("#sliderImg2")
var speed = defaultSettings.transitionSpeed; //Transition speed
now.fadeOut(speed);
next.fadeIn(speed,function(){
document.getElementById("sliderImg").src = document.getElementById("sliderImg2").src;
$("#sliderImg").css('display','block');
$("#sliderImg2").css('display','none');
});
}
function startSlide() {
console.log('start');
theInterval = setInterval(function () {
cycleImages(images);
}, defaultSettings.sliderSpeed);
// Set interval time
};
var stopSlide = function () { // Stop slides on hover
console.log('stop');
if (defaultSettings.pauseWithMouse) {
clearInterval(theInterval);
}
};
$('#sliderImg').on('mouseover', function () { // Stop slides on mouseover
stopSlide();
});
$('#sliderImg').on('mouseout', function () { // Continue with slides on mouseout
startSlide();
});
});
CSS:
body{
margin: 0;
}
main {
max-width: 100%;
height: 737px;
margin: auto;
font-family: arial;
position: relative;
color: white;
}
#slider {
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
}
#slider img {display:none; position: absolute; top: 0; left: 0;}
#slider img:first-child {display:block;}
#slider img:nth-child(2) {display:none;}
The flash effect it's because your next picture is already visible before the call of fadeIn() function, you fix it with add next.hide() just before now.fadeOut().
$(function () {
var theInterval; // Slide speed
var images = new Array();
var counter = 1;
var defaultSettings = {
"sliderContainer": "#slider" // SliderContainer
, "pauseWithMouse": true // Turn on/off pause with mouse
, "sliderSpeed": 3000 // Slide speed
, "transitionSpeed": 800 // transition speed
};
// intialize slider
// if myImages exists then
images = myImages;
if (images.length > 0) {
$(defaultSettings.sliderContainer).append('<img id="sliderImg" width="900" src="' + images[0] + '" />');
startSlide(images);
}
function cycleImages(images) {
if (counter >= images.length) {
counter = 0;
}
console.log(counter);
document.getElementById("sliderImg").src = images[counter];
counter++;
var images = $('#sliderImg')
var now = images.filter(':visible')
var next = now.next().length ? now.next() : images.first()
var speed = defaultSettings.transitionSpeed; //Transition speed
next.hide();
now.fadeOut(speed);
next.fadeIn(speed);
}
function startSlide() {
console.log('start');
theInterval = setInterval(function () {
cycleImages(images);
}, defaultSettings.sliderSpeed);
// Set interval time
};
var stopSlide = function () { // Stop slides on hover
console.log('stop');
if (defaultSettings.pauseWithMouse) {
clearInterval(theInterval);
}
};
$('#sliderImg').on('mouseover', function () { // Stop slides on mouseover
stopSlide();
});
$('#sliderImg').on('mouseout', function () { // Continue with slides on mouseout
startSlide();
});
});
body{
margin: 0;
}
main {
max-width: 100%;
height: 737px;
margin: auto;
font-family: arial;
position: relative;
color: white;
}
#slider {
width: 100%;
height: 100%;
overflow: hidden;
position: relative;
}
#slider img {display:none; position: absolute; top: 0; left: 0;}
#slider img:first-child {display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
var myImages = ["https://s4.postimg.org/45u9pqnml/slide1.jpg", "https://s11.postimg.org/f3qwh4syb/slide2.jpg", "https://s24.postimg.org/b365xoq7p/slide3.jpg"];
</script>
<main>
<div id="slider">
</div>
</main>
try to change transitionspeed to 0