Animation gets fail - javascript

i have a script here that animate 3 divs containing product came from the database. It animate well when the page load in the first time but my problem is its not animate well after a min and everytime i refresh the page.
<html>
<script src='jquery.js'></script>
<script>
$(document).ready(function(){
$("#Slide2").hide();
$("#Slide3").hide();
});
var h = 1;
var x = setTimeout(show2, 3000);
function show1()
{
h = 1;
$("#Slide1").show();
$("#Slide2").hide();
$("#Slide3").hide();
$("#Slide1").css("left", "-400px");
$("#Slide1").animate({left:'-1px'});
clearTimeout(x);
x = setTimeout(show2, 3000);
}
function show2()
{
if(h <= 2)
{
h = 2;
$("#Slide2").show();
$("#Slide1").hide();
$("#Slide3").hide();
$("#Slide2").css("right", "-400px");
$("#Slide2").animate({right:'-1px'});
clearTimeout(x);
x = setTimeout(show3, 3000);
}
else
{
h = 2;
$("#Slide2").show();
$("#Slide1").hide();
$("#Slide3").hide();
$("#Slide2").css("left", "-400px");
$("#Slide2").animate({left:'-1px'});
clearTimeout(x);
x = setTimeout(show3, 3000);
}
}
function show3()
{
h = 3;
$("#Slide3").show();
$("#Slide2").hide();
$("#Slide1").hide();
$("#Slide3").css("right", "-400px");
$("#Slide3").animate({right:'-1px'});
clearTimeout(x);
x = setTimeout(show1, 3000);
}
</script>
<style>
#Slide1 , #Slide2, #Slide3
{
width:530px;
height:100px;
position:relative;
background:blue;
}
#container
{
width:500px;
margin:auto;
border:1pt solid black;
overflow:hidden;
height:auto;
}
</style>
<body>
<div id='container'>
<button onclick="check1()">1</button>
<button onclick="check2()">2</button>
<button onclick="check3()">3</button>
<br></br>
<div style='width:530px;margin:auto'>
<div id='Slide1'>
<div style='width:120px;height:100px;float:left;margin-left:10px;background:#ff0'></div>
<div style='width:120px;height:100px;float:left;margin-left:10px;background:#ff0'></div>
<div style='width:120px;height:100px;float:left;margin-left:10px;background:#ff0'></div>
<div style='width:120px;height:100px;float:left;margin-left:10px;margin-right:10px;background:#ff0'></div>
</div>
<div id='Slide2' >
<div style='width:120px;height:100px;float:left;margin-left:10px;background:green'></div>
<div style='width:120px;height:100px;float:left;margin-left:10px;background:green'></div>
<div style='width:120px;height:100px;float:left;margin-left:10px;background:green'></div>
<div style='width:120px;height:100px;float:left;margin-left:10px;margin-right:10px;background:green'></div>
</div>
<div id='Slide3' >
<div style='width:120px;height:100px;float:left;margin-left:10px;background:red'></div>
<div style='width:120px;height:100px;float:left;margin-left:10px;background:red'></div>
<div style='width:120px;height:100px;float:left;margin-left:10px;background:red'></div>
<div style='width:120px;height:100px;float:left;margin-left:10px;margin-right:10px;background:red'></div>
</div>
</div>
</div>
</body>
</html>

You are not clearing your previous setInterval before starting new setInterval. Use clearInterval(x) before every setInterval in your show1(), show2() and show3() . hope it ll help.
You have redundant if else loop in your show2() . check it here (http://jsfiddle.net/cJ9FK/)
Hope it'll help, Thank you

Related

Showing an element for 5 seconds, then hide and show next element

This is what I've tried so far, but it just shows all the elements at once:
i1 = document.getElementById('img_1');
i2 = document.getElementById('img_2');
i3 = document.getElementById('img_3');
i4 = document.getElementById('img_4');
i5 = document.getElementById('img_5');
myarr = [i1,i2,i3,i4,i5];
for (i=0; i<myarr.length;i++) {
$(myarr[i]).show().delay(5000).fadeOut();
}
I assume you are trying to achieve an endless loop.
I think you should use interval in that case, and do fadeOut/fadeIn of elements.
i1 = document.getElementById('img_1');
i2 = document.getElementById('img_2');
i3 = document.getElementById('img_3');
i4 = document.getElementById('img_4');
i5 = document.getElementById('img_5');
let myarr = [i1, i2, i3, i4, i5];
let active = 1;
setInterval(() => {
$(myarr[active - 1]).fadeOut(500)
if (active >= myarr.length) {
active = 0
}
setTimeout(() => {
$(myarr[active]).fadeIn(500);
active = active + 1;
}, 500)
}, 5000)
What this does, is updates elements every 5 sec to next element, if it reached the end, it resets it to zero.
Checkout this fiddle
You can use async and await.
Another this you can improve is that. You can add same class to all images you want to show in series. If you want to select all by id you can use Attribute Selectors.
const myarr = document.querySelectorAll('img[id^=img]');
I have used same class rather than id
const arr = [...document.querySelectorAll('.test')];
(async function(){
for (let i=0; i<arr.length;i++) {
await new Promise(res => {
setTimeout(() => {
$(arr[i]).show().fadeOut();
res();
},2000)
})
}
})()
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="test">Test 1</div>
<div class="test">Test 2</div>
<div class="test">Test 3</div>
let count = 1;
setInterval(()=>{
document.querySelectorAll("*[id*='img_']").forEach((elem)=> elem.style.display="none");
document.getElementById(`img_${count}`).style.display="";
if(count<4) count++;
else count = 1;
},1000)
<div id="img_1">Image 1</div>
<div id="img_2" style="display:none">Image 2</div>
<div id="img_3" style="display:none">Image 3</div>
<div id="img_4" style="display:none">Image 4</div>
Vanilla Javascript solution!
You forgot to show your element after fadeOut. Here you can achieve it:
// show first element
$('img').eq(0).show();
$('img').each(function () {
// your delay
$('img').delay(5000).fadeOut();
// make sure next element is image
if ($(this).next()[0].tagName === 'IMG') {
// show next element
$(this).next().fadeIn();
}
});
img {
display: none;
position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<img src="https://picsum.photos/id/5/50" />
<img src="https://picsum.photos/id/10/50" />
<img src="https://picsum.photos/id/30/50" />
<img src="https://picsum.photos/id/0/50" />
<img src="https://picsum.photos/id/150/50" />
<img src="https://picsum.photos/id/1000/50" />
var basicVal =0;
$(document).ready(function(){
$('.wrapper img').eq( basicVal ).show();
var setTime =setInterval(function(){
if( basicVal < $('.wrapper img').length - 1){
$('.wrapper img').eq(basicVal ).hide();
basicVal++;
$('.wrapper img').eq(basicVal).show();
}else{
clearTimeout(setTime);
}
console.log();
}, 5000);
});
.wrapper{
width: 100%;
float: left;
}
.wrapper img{
width: 50%;
height: 300px;
object-fit: cover;
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
<img src="https://images.pexels.com/photos/34950/pexels-photo.jpg?auto=compress&cs=tinysrgb&dpr=1&w=500" alt="">
<img src="http://www.desktopwallpaperhd.net/wallpapers/0/4/landscapes-wallpaper-fengguangbizhi-fengjingbizhi-picture-image-1316.jpg" alt="">
<img src="http://trustbanksuriname.com/wp-content/uploads/2019/04/pony-picture-guide-to-native-pony-breeds-little-pony-cartoon-pictures.jpg" alt="">
<img src="https://www.bigfoto.com/stones-background.jpg" alt="">
<img src="https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQulscf1nNOpaI1tElZgKTTSAl_ZcL_i1VwLDojgKzqjSTMofsqPw" alt="">
</div>
check this out I use some little bit of jquery and setInterval function to change in every 5000ms
You may use setTimeout for achieving this effect.
<div id="container">
<div class="block" id="img_1"></div>
<div class="block" id="img_2"></div>
<div class="block" id="img_3"></div>
<div class="block" id="img_4"></div>
<div class="block" id="img_5"></div>
</div>
.block{
width:100px;
height:100px;
display: inline-block;
margin:10px;
background: lightblue;
visibility: hidden;
}
And then,
$('.block').each(function(index, value) {
setTimeout(function() {
$(value).css("visibility", "visible");
$(value).show().delay(1000).fadeOut();
}, 2000 * (index + 1));
});

JavaScript - periodically change "active" image

I have 4 pictures and want them to periodically change class (I have .active class, which is similar to hover).
.active,
.pic:hover{
position: absolute;
border: 1px solid black;
transform: scale(1.1);
transition: transform .2s;
}
Basically I need the first picture to have the class active and after some time change it so the next picture has the class and the first one lose it.
Is something like that even possible?
Picture in HTML:
<div class="products">
<a href="http://example.com/produkt1">
<img class="pic" src="image.jpg" alt="image" width="75" height="75">
</a>
</div>
and JS:
productIndex = 0;
slideshow();
function slideshow(){
var i;
var pic = document.getElementsByClassName("pic");
for(i = 0; i < pic.length; i++){
pic[i].className = pic[i].className.replace("active", "");
}
productIndex++;
if(productIndex > pic.length){
productIndex = 1;
}
pic[productIndex-1].className += active;
setInterval(slideshow, 2000);
}
You can use setInterval to run a function periodically that will change the active class. Something like this (psuedo-code):
var imageArray = [];
var activeIndex = 0;
setInterval(function(){
imageArray[activeIndex].removeClass('active');
activeIndex++;
activeIndex %= 4;
imageArray[activeIndex].addClass('active');
}, 5000);
The number value passed in as a parameter is how many milliseconds to wait before running the function again. In this example, 5 seconds will pass between the classes are changed.
setInterval Reference
This is ugly but it could work for super basic ... You just need to update the div blocks with images if necessary. Uses jquery...
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<style>
div {
width:50px;
height:50px;
background-color: black;
margin-bottom:10px;
}
.active {
background-color: red;
}
</style>
</head>
<body>
<div id="pic1"></div>
<div id="pic2"></div>
<div id="pic3"></div>
<div id="pic4"></div>
<script>
let lastActive = 0;
setInterval(()=>{
$('div').removeClass('active');
if(lastActive === 0){
$('#pic1').addClass('active');
lastActive = 1;
}
else if(lastActive === 1){
$('#pic2').addClass('active');
lastActive = 2;
}
else if(lastActive === 2){
$('#pic3').addClass('active');
lastActive = 3;
}
else if(lastActive === 3){
$('#pic3').addClass('active');
lastActive = 4;
}
else if(lastActive === 4){
$('#pic1').addClass('active');
lastActive = 1;
}
}, 500)
</script>
</body>
</html>
Matt L. has a good point here. Your code has the setInterval inside your slideshow function, otherwise it's fine.
productIndex = 0;
slideshow();
function slideshow(){
var i;
var pic = document.getElementsByClassName("pic");
for(i = 0; i < pic.length; i++){
pic[i].className = pic[i].className.replace("active", "");
}
productIndex++;
if(productIndex > pic.length){
productIndex = 1;
}
pic[productIndex-1].className += active;
}
setInterval(slideshow, 2000);
could probably work. Matt's answer is a lot better, and I came up with something similar, which is testable on jsfiddle.
You could do it like this for example:
$(document).ready(function() {
setInterval(function() {
var active = $('.active');
active.nextOrFirst().addClass('active');
active.removeClass('active');
}, 3000);
});
$.fn.nextOrFirst = function(selector)
{
var next = this.next(selector);
return (next.length) ? next : this.prevAll(selector).last();
};
.active,
.pic:hover{
border: 1px solid black;
}
.pic {
width: 150px;
margin: 10px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="image-container">
<img class="pic active" src="https://via.placeholder.com/350x150">
<img class="pic" src="https://via.placeholder.com/350x150">
<img class="pic" src="https://via.placeholder.com/350x150">
<img class="pic" src="https://via.placeholder.com/350x150">
</div>
Edit:
This, instead of most other solutions, will work with any amount of items. To use it only on pictures just specify via selector in the function.
Checkout this working example. I've made use of a combination of setInterval and setTimeout.
$(window).ready(()=>{
// get all the images inside the image-container div
let $images = $('.image-container').find('.image');
let currImage = 0;
// execute this code every 2 seconds
window.setInterval(()=>{
// add the active class to the current image
$($images[currImage]).addClass('active');
setTimeout(()=>{
// execute the code here after 1.5 seconds
// remove the active class from the previous image
$($images[currImage-1]).removeClass('active');
}, 1500);
// make sure we don't go over the number of elements in the collection
currImage = currImage >= $images.length ? 0 : currImage + 1;
}, 2000);
});
.image.active {
border: thin solid blue;
}
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<div class="image-container" class="">
<img src="https://via.placeholder.com/200x200" class="image active">
<img src="https://via.placeholder.com/200x200" class="image">
<img src="https://via.placeholder.com/200x200" class="image">
<img src="https://via.placeholder.com/200x200" class="image">
</div>
Do make sure that the code in setTimeout will execute before the next interval. Meaning, the time set for setTimeout is always less than setInterval's :)
Yes it is possible:
function carousel() {
var images = document.querySelectorAll(".container img");
for(var i = 0; i < images.length; i++) {
if(images[i].classList.contains("active")) {
images[i].classList.remove("active");
if(i == images.length - 1) {
images[0].classList.add("active");
} else {
images[i + 1].classList.add("active");
}
break;
}
}
}
setInterval(carousel,1000);
img {
width: 100px;
margin-left: 10px;
transition: .2s;
}
.active {
transform: scale(1.1);
}
<div class="container">
<img src="https://i.stack.imgur.com/cb20A.png" class="active"/>
<img src="https://i.stack.imgur.com/cb20A.png"/>
<img src="https://i.stack.imgur.com/cb20A.png"/>
<img src="https://i.stack.imgur.com/cb20A.png"/>
</div>
You can then replace the .active class by whatever you want.

Display text in time intervals with CSS and JS

I would like to create, using the setInterval() JS function, a visual effect that displays text one character at the time with an interval of 100ms per character, on an Angular application.
Note that this happens in the index.html within the <app-root> tags, so it will appear only while the app is bootstrapped.
After reading the setInterval() page i thought that this would make the job, so this is my code:
var divs=['rBox','aBox','tBox','sBox'];
var index=-1;
function displayChars(){
for(container of divs){
document.getElementById(container).style.visibility='hidden';
}
var fun = setInterval(display,100);
}
function display(){
if(index < 4){
document.getElementById(divs[++index]).style.visibility='visible'
}else{
clearInterval(fun);
}
}
displayChars();
<app-root>
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
</app-root>
But it does not display anything, the divs containing the numbers are there with visibility set to hidden but it seems like they are never set to visible
I can't see where the problem lies. If I look at the code from an algorithmic point of view, I guess I probably don't understand very well the inner working of setInterval().
fun was not declared globally
And index was incremented too much
A rough update to the code:
var divs=['rBox','aBox','tBox','sBox'];
var index=-1;
var fun
function displayChars(){
for(container of divs){
document.getElementById(container).style.visibility='hidden';
}
fun = setInterval(display,100);
}
function display(){
if(index < 3){
document.getElementById(divs[++index]).style.visibility='visible'
}else{
clearInterval(fun);
}
}
displayChars()
<app-root>
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
</app-root>
After minor modifications it's working, see below. I changed index to start at 0 and to be used with divs[index++] (so use-then-increment), and to compare it with divs.length instead of hardcoded 4. Also I put variable fun at the global level.
var divs = ['rBox', 'aBox', 'tBox', 'sBox'];
var index = 0;
var fun = -1; // timer handle
function displayChars() {
for (container of divs) {
document.getElementById(container).style.visibility = 'hidden';
}
fun = setInterval(display, 100);
}
function display() {
if (index < divs.length) {
document.getElementById(divs[index++]).style.visibility = 'visible'
} else {
clearInterval(fun);
}
}
displayChars();
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
Your variable fun needs to be global, otherwise display() can't
access it
Don't forget to declare container in your for...of loop as an actual variable
You where incrementing index too often
var divs = ['rBox', 'aBox', 'tBox', 'sBox'];
var index = -1;
var fun;
function displayChars() {
for (var container of divs) {
document.getElementById(container).style.visibility = 'hidden';
}
fun = setInterval(display, 100);
}
function display() {
if (index < 3) {
document.getElementById(divs[++index]).style.visibility = 'visible';
} else {
clearInterval(fun);
}
}
displayChars();
<app-root>
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
</app-root>
Pure CSS solution, if an option, looks something like this:
.rats-div > div {
opacity: 0; /* or "visibility: hidden" */
animation: opacity .1s forwards;
}
.rats-div > div:nth-child(2) {animation-delay: .1s}
.rats-div > div:nth-child(3) {animation-delay: .2s}
.rats-div > div:nth-child(4) {animation-delay: .3s}
#keyframes opacity {
to {opacity: 1} /* or "visibility: visible / initial" */
}
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
var divs=['rBox','aBox','tBox','sBox'];
var index=0;
var fun=null;
function displayChars(){
for(container of divs){
document.getElementById(container).style.visibility='hidden';
}
fun = setInterval(display,100);
}
function display(){
if(index < 4){
document.getElementById(divs[index]).style.visibility='visible'
index++;
}else{
clearInterval(fun);
}
}
displayChars();
<app-root>
<div class="rats-div">
<div id="rBox">1</div>
<div id="aBox">2</div>
<div id="tBox">3</div>
<div id="sBox">4..</div>
</div>
</app-root>
try this code. it should do your job.

Reset counter and start over again

I am trying to make a quiz in jquery which takes answer from the user, checks it with the correct answer and then shows the result with the score.
I want my quiz to start over again after finishing one round. The code works fine for first round but when I start it again, it shows only the first question and doesn't proceed.
What is going wrong ??
The link of fiddle is here
HTML
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="score">Score: <span id="scr"></span>/10</div>
<div class="correct">Correct</div>
<div class="incorrect">Incorrect</div>
<div class="qstart">start</div>
<div class="qarea">
<div class="question">Father</div>
<div class="canswer">Vater</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">My father</div>
<div class="canswer">Mein Vater</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Land</div>
<div class="canswer">Land</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Mother</div>
<div class="canswer">Mutter</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Brother</div>
<div class="canswer">Bruder</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">City</div>
<div class="canswer">Stadt</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Woman</div>
<div class="canswer">Frau</div>
<textarea class="abox"></textarea>
</div>
<div class="qarea">
<div class="question">Man</div>
<div class="canswer">Mann</div>
<textarea class="abox"></textarea>
</div>
<div class="qsubmit">submit</div>
<div class="startagain">startagain</div>
CSS
.score {
float:right;
display:block;
}
.question {
float:left;
}
.next {
float:left;
margin:10px;
}
.qsubmit {
float:left;
margin:10px;
}
.correct {
float:right;
display:block;
}
Jquery
$(document).ready(function () {
//declare variables
var qarea = $(".qarea");
var totalqarea = qarea.length - 1;
var startagain = $(".startagain");
var canswer = $(".canswer")
var qsubmit = $(".qsubmit");
var counter = 0;
//hide unrequired
qsubmit.hide();
startagain.hide();
$("startagain")
$(".correct,.incorrect").hide();
qsubmit.hide();
$(".canswer").hide();
qarea.hide();
var qstart = $(".qstart");
//intiate click on start
qstart.click(function () {
var counter = 0;
qsubmit.show();
qarea.eq(counter).show();
qstart.hide();
var i = 1;
//loop(); function loop()
//initate submit
qsubmit.bind("click", function () {
var ma = canswer.eq(counter).text();
var mal = ma.toLowerCase();
var ua = $("textarea").eq(counter).val();
var ual = ua.toLowerCase();
var n = mal.localeCompare(ual);
// checks correct answer and gives score
if (n == 0) {
$(".correct").show();
$("#scr").text(i);
i = i + 1;
qsubmit.html("continue");
//gives incorrect
} else {
$(".incorrect").text("correct answer is " + ma).show();
qsubmit.html("continue");
}
// increase counter
counter = counter + 1;
qarea.eq(counter - 1).hide();
qarea.eq(counter).show();
if (totalqarea == counter) {
qsubmit.hide();
qstart.text("start again").show();
qarea.eq(counter).hide()
qstart.click(function () {
//loop();return;
})
}
})
})
})
Reset your counter and it will work.
if (totalqarea == counter) {
qsubmit.hide();
qstart.text("start again").show();
qarea.eq(counter).hide()
counter = 0;

Change Image on Scroll Position

I would like to change an image on a certain scroll position. For example:
Scroll 100px show img1.jpg
Scroll 200px show img2.jpg
Scroll 300px show img3.jpg
Here I found an example what I mean.
Any ideas?
You can use the onScroll event to listen for scrolling, check at what position the scrollbar is and make the image change or whatever your heart desires. You can read more about onScroll event here. A basic code will be something like this:
var onScrollHandler = function() {
var newImageUrl = yourImageElement.src;
var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
if (scrollTop > 100) {
newImageUrl = "img1.jpg"
}
if (scrollTop > 200) {
newImageUrl = "img2.jpg"
}
if (scrollTop > 300) {
newImageUrl = "img3.jpg"
}
yourImageElement.src = newImageUrl;
};
object.addEventListener ("scroll", onScrollHandler);
Of course yourImageElement should be replaced with the image element you want to change.
If you have jQuery availble you can use the .scroll() method instead of the event listener and the .scrollTop() to get the scrollbar position.
Also, you might want to look at some scroll/paralex libraries like skrollr.
$(window).on("scroll touchmove", function()
{
if ($(document).scrollTop() >= $("#one").position().top && $(document).scrollTop() < $("#two").position().top )
{
$('body').css('background-image', 'url(https://4.bp.blogspot.com/-Ivk46EkgQfk/WWjbo4TdJbI/AAAAAAAAFUo/gUD7JABklsIA1gWIr5LS1slyY4QuTMkEwCLcBGAs/s1600/gambar%2Bwallpaper%2Bmobil.jpg)')
};
if ($(document).scrollTop() >= $("#two").position().top && $(document).scrollTop() < $("#three").position().top)
{
$('body').css('background-image', 'url(https://i1.wp.com/cdn.catawiki.net/assets/marketing/uploads-files/45485-8bdcc8479f93d5a247ab844321b8b9d5e53c49a9-story_inline_image.jpg)')
};
if ($(document).scrollTop() >= $("#three").position().top && $(document).scrollTop() < $("#four").position().top )
{
$('body').css('background-image', 'url(https://s-media-cache-ak0.pinimg.com/originals/e1/7a/03/e17a0385726db90de1854177d4af2b4f.jpg)')
};
if ($(document).scrollTop() >= $("#four").position().top)
{
$('body').css('background-image', 'url(https://www.wallpaperup.com/uploads/wallpapers/2015/02/13/621414/6fc33c3ae65a58f9bb137f5cf011aebc.jpg)')
};
});
*{
margin:0;
padding:0;
}
.main{
width:100%;
height:100vh;
background-image:url('https://4.bp.blogspot.com/-Ivk46EkgQfk/WWjbo4TdJbI/AAAAAAAAFUo/gUD7JABklsIA1gWIr5LS1slyY4QuTMkEwCLcBGAs/s1600/gambar%2Bwallpaper%2Bmobil.jpg');
background-size:100% 100%;
background-attachment:fixed;
transition: 1000ms;
}
section{
width: 100%;
min-height: 1px;
}
.content{
width:50%;
min-height:1px;margin-top:10%;
margin-left:10%;
color:white;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body class='main'>
<section id="one">
<div class='content'>
<h1 style='font-size:5vw;'>first heading</h1>
<p style='font-size:3vw;' >description</p>
</div>
</section>
<section id="two" style='margin-top:100vh'>
<div class='content'>
<h1 style='font-size:5vw;'>second heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="three" style='margin-top:100vh' >
<div class='content'>
<h1 style='font-size:5vw;'>third heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="four" style='margin-top:100vh' >
<div class='content' style='margin-bottom:10%;'>
<h1 style='font-size:5vw;'>fourth heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
</body>
</html>
documentation
create a web folder first.
create a img sub folder // place all images into this folder
now create three files // in web folder
index.html
css.css
js.js
copy code given bellow and paste it.
save the program.
finally run the program
click on this link to see the video :https://www.youtube.com/watch?v=V97wCVY_SrQ
visit our website for full documentation :https://nozzons.blogspot.com/
index.html
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href='css.css' rel='stylesheet' type='text/css'/>
<script src='js.js'></script>
</head>
<body class='main'>
<section id="one">
<div class='content'>
<h1 style='font-size:5vw;'>first heading</h1>
<p style='font-size:3vw;' >description</p>
</div>
</section>
<section id="two" style='margin-top:100vh'>
<div class='content'>
<h1 style='font-size:5vw;'>second heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="three" style='margin-top:100vh' >
<div class='content'>
<h1 style='font-size:5vw;'>third heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
<section id="four" style='margin-top:100vh' >
<div class='content' style='margin-bottom:10%;'>
<h1 style='font-size:5vw;'>fourth heading</h1>
<p style='font-size:3vw;'>description</p>
</div>
</section>
</body>
</html>
css.css
*{
margin:0;
padding:0;
}
.main{
width:100%;
height:100vh;
background-image:url('img/img_one.jpg');
background-size:100% 100%;
background-attachment:fixed;
transition: 1000ms;
}
section{
width: 100%;
min-height: 1px;
}
.content{
width:50%;
min-height:1px;margin-top:10%;
margin-left:10%;
color:white;
}
js.js
$(window).on("scroll touchmove", function()
{
if ($(document).scrollTop() >= $("#one").position().top && $(document).scrollTop() < $("#two").position().top )
{
$('body').css('background-image', 'url(img/img_one.jpg)')
};
if ($(document).scrollTop() >= $("#two").position().top && $(document).scrollTop() < $("#three").position().top)
{
$('body').css('background-image', 'url(img/img_two.jpg)')
};
if ($(document).scrollTop() >= $("#three").position().top && $(document).scrollTop() < $("#four").position().top )
{
$('body').css('background-image', 'url(img/img_three.jpg)')
};
if ($(document).scrollTop() >= $("#four").position().top)
{
$('body').css('background-image', 'url(img/img_four.jpg)')
};
});
So i am just answering this old thread because I was trying to implement the same thing on my website but i found it a bit difficult to implement it so I made a function of my own , its a bit easier to implement and understand but a bit buggy, For instance: if the user use the scroll bar instead of scroll wheel of the mouse the image will not change , hope it helps you :
<html>
<head>
<script>
function f() {
t1.src = "https://igu3ss.files.wordpress.com/2012/09/chess_king_4.jpg"
t1.height = "319"
t1.width = "330"
}
function f2() {
t1.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/d/d3/Chess_piece_-_Black_queen.JPG/130px-Chess_piece_-_Black_queen.JPG"
t1.height = "319"
t1.width = "330"
}
function f3() {
t1.src = "https://asmoodle.asmadrid.org/blog/s16240/wp-content/uploads/sites/56/2014/12/protourney_knight_black_400.jpg"
t1.height = "244"
t1.width = "330"
}
function f4() {
t1.src = "https://thumbs.dreamstime.com/x/chess-knight-white-background-29811348.jpg"
t1.height = "244"
t1.width = "350"
}
function f5() {
t1.src = "http://cdn.craftsy.com/upload/3703789/pattern/115774/full_7439_115774_ChessKnightMachineEmbroideryDesign_1.jpg"
t1.height = "319"
t1.width = "350"
}
</script>
</head>
<body>
<div align="center" style="position: fixed; z-index: 20; left:38.5%; top:200">
<img src="no.png" height="319" width="330" name="t1">
</div>
</div>
<div class="container" onmouseover="f3()" style="padding:0; margin:0; width:100%;">
<img src="https://pixabay.com/static/uploads/photo/2016/01/11/22/05/background-1134468_960_720.jpg" width="100%">
</div>
<br>
<br>
<div class="container" onmouseover="f4()" style="padding:0; margin:0; width:100%;">
<img src="https://image.freepik.com/free-photo/lens-flare-abstract-backgound_21276999.jpg" width="100%">
</div>
<br>
<br>
<div class="container" onmouseover="f5()" style="padding:0; margin:0; width:100%;">
<img src="https://image.freepik.com/free-photo/lens-flare-abstract-backgound_21276999.jpg" width="100%">
</div>
<br>
<br>
<div class="container" onmouseover="f()" style="padding:0; margin:0; width:100%;"></div>
</body></html>
Cheers!!
Ha[ppy] Coding.

Categories