i am trying to find a solution on how i can execute my script when div appears, in this particular case i have a div that is section counter and i want when this div appears to start counting my stats (that is my script) and i don't know how to do that.
This is my section counter:
/**********************
Section Counter
**********************/
.section-counter{
height: 380px;
background-image: url('../imgAboutGuitars/section-counter-bg.jpg');
/* Center and scale the image nicely */
background-position: center;
background-repeat: no-repeat;
background-size: cover;
background-attachment: fixed;
}
.overlay{
width: 100%;
height: 380px;
position: absolute;
background-color: #000;
opacity: .5;
}
.icon-container{
width: 80px;
height: 80px;
margin: 0 auto;
position: relative;
margin-bottom: 20px;
z-index: 0;
}
.icon-container:before {
content: '';
position: absolute;
height: 100%;
width: 100%;
top: 0;
left: 0;
transition: 0.5s ease;
border: 2px solid #c49b63;
}
.icon-container:hover:before {
transform: rotate(135deg);
background: #fff;
}
.box i{
font-size: 40px;
color: #c49b63;
margin-top: 20px;
position: relative;
}
.icon-container:hover i{
color: #000;
}
.counter-box {
display: block;
position:relative;
margin-top: 20px;
padding-top: 1em;
}
.counter {
display: block;
font-size: 32px;
font-weight: 700;
color: #c49b63;
line-height: 28px
}
.counter-box span {
color: #bfbfbf;
font-size: 18px;
font-weight: 500;
margin-top: 0.5em;
display: block;
}
<!-- Section Counter -->
<div class="overlay"></div>
<div class="container-fluid section-counter">
<div class="row justify-content-center h-100">
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-4 col-4 my-auto box text-center">
<div class="icon-container">
<i class="fa fa-thumbs-o-up"></i>
<div class="counter-box">
<strong class="counter counterHappy">0</strong>
<span>Happy Customers</span>
</div>
</div>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-4 col-4 my-auto box text-center">
<div class="icon-container">
<i class="fa fa-check"></i>
<div class="counter-box">
<strong class="counter counterConstructed">0</strong>
<span>Basses Guitars</span>
</div>
</div>
</div>
<div class="col-xl-2 col-lg-3 col-md-4 col-sm-4 col-4 my-auto box text-center">
<div class="icon-container">
<i class="fa fa-shopping-cart"></i>
<div class="counter-box">
<strong class="counter counterOrders">0</strong>
<span>Orders</span>
</div>
</div>
</div>
</div>
</div>
As you can see the stats is zero for every icon, the script for counting is below here:
// getting the products
class countProducts{
async fetchProducts(){
try{
var result = await fetch('./json/products.json')
var data = await result.json();
var products = data.items;
return products;
}catch (error){
console.log('error');
}
}
}
class uiCount{
getProducts(products){
this.countDisplay(products);
}
countDisplay(products){
//Speed of Counter
const speed = 200;
//Varible for type of Guitar
var typeGuitar = document.querySelector('.wallpaper_text').innerText;
//Array for every type of Guitar
var arrayOfElectrical = 0;
var arrayOfAcoustic = 0;
var arrayOfBasses = 0;
const counterGuitars = document.querySelectorAll('.counterConstructed');
for(var i=0;i < products.length;i++){
//Count if Type is Electrical
if(typeGuitar == "Electrical Type"){
if(products[i].type == "Electrical"){
arrayOfElectrical++;
}
//Second Column of Section Counter
counterGuitars.forEach((counter)=>{
counter.innerText = '0';
const updateCounter = () =>{
const target = arrayOfElectrical;
const count = +counter.innerText;
const increment = target / 200;
if(count < target){
counter.innerText = `${Math.ceil(count + increment)}`;
setTimeout(updateCounter,1);
}else{
counter.innerText = target;
}
};
updateCounter();
});
}
//Count if Type is Acoustic
else if(typeGuitar == "Acoustic Type"){
if(products[i].type == "Acoustics"){
arrayOfAcoustic++;
}
//Second Column of Section Counter
counterGuitars.forEach((counter)=>{
counter.innerText = '0';
const updateCounter = () =>{
const target = arrayOfAcoustic;
const count = +counter.innerText;
const increment = target / 200;
if(count < target){
counter.innerText = `${Math.ceil(count + increment)}`;
setTimeout(updateCounter,1);
}else{
counter.innerText = target;
}
};
updateCounter();
});
}
//Count if Type is Basses
else if(typeGuitar == "Basses Type"){
if(products[i].type == "Basses"){
arrayOfBasses++;
}
//Second Column of Section Counter
counterGuitars.forEach((counter)=>{
counter.innerText = '0';
const updateCounter = () =>{
const target = arrayOfBasses;
const count = +counter.innerText;
const increment = target / 200;
if(count < target){
counter.innerText = `${Math.ceil(count + increment)}`;
setTimeout(updateCounter,1);
}else{
counter.innerText = target;
}
};
updateCounter();
});
}
}
//First Column of Section Counter
const counterHappy = document.querySelectorAll('.counterHappy');
counterHappy.forEach((counter)=>{
counter.innerText = '0';
const updateCounter = () =>{
const target = 3800;
const count = +counter.innerText;
const increment = target / 200;
if(count < target){
counter.innerText = `${Math.ceil(count + increment)}`;
setTimeout(updateCounter,1);
}else{
counter.innerText = target;
}
};
updateCounter();
});
//Third Column of Section Counter
const counterOrders = document.querySelectorAll('.counterOrders');
counterOrders.forEach((counter)=>{
counter.innerText = '0';
const updateCounter = () =>{
const target = 7500;
const count = +counter.innerText;
const increment = target / 200;
if(count < target){
counter.innerText = `${Math.ceil(count + increment)}`;
setTimeout(updateCounter,1);
}else{
counter.innerText = target;
}
};
updateCounter();
});
}
}
//saving the products
class saveCountProducts{
static saveProducts(products){
return products;
}
}
document.addEventListener('DOMContentLoaded', () => {
const products = new countProducts();
const ui = new uiCount();
const storage = new saveCountProducts();
products.fetchProducts();
products.fetchProducts().then(products => {
saveCountProducts.saveProducts(products);
ui.getProducts(products);
});
})
Therefore, when page loads the section starts counting as a result when the user reaches on section counter the stats have already counted, so i want when the user reach on this div then and only stats would start counting.
PS: Sorry in advance for my english, if you have any question i will appreciate it if you express it!
Related
I'm trying to make a count down so that every 20 sec an alert pops up. I want it to go from 20 to 0 to 20 over and over. I have it working, but it only works once. The rage function dosen't need to be changed, it's the msg function i'm having trouble with. Here's my code.
function rage() {
var i = document.getElementsByName("msg")[6];
var message = document.getElementById("message");
const affichemsg = document.querySelector("msg");
for (i = 0; i < 1; i++) {
message.innerHTML += "Es-tu près ";
}
}
setInterval(rage, 350);
var decompteur = setInterval(msg, 1000);
var temps;
function msg() {
var idTemps = document.getElementById("temps");
temps = parseInt(idTemps.innerHTML);
temps = temps - 1;
idTemps.innerHTML = temps;
if (--temps <= 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
clearInterval(temps);
msg();
idTemps = 20;
var decompteur = setInterval(msg, 1000);
}
}
.titre2 {
width: 650px;
margin: auto;
text-align: center;
border-radius: 35px;
color: #000000;
background-color: #ff0000;
padding: 5px;
margin-bottom: 30px;
}
.bouton {
transition-duration: 0.4s;
border-width: 1px;
cursor: pointer;
}
.boutonOui {
background-color: rgb(234, 234, 234);
}
.boutonOui:hover {
background-color: rgb(177, 177, 177);
}
<div class="header">
<h1 class="titre2">Es-tu près</h1>
</div>
<button
class="bouton boutonOui"
id="boutonOui"
onclick="window.location.href='jeu_educatifs2.html'"
>
Oui
</button>
<div id="temps">20</div>
<div id="message"></div>
<div id="msg" value="6"></div>
the first problem here is that you don't use correctly the method clearInterval. It takes as argument the id of the "timer" created with setInterval. setInterval return directly the id so actually stored it in your variable decompteur and you should use something like that to clear the timer : clearInterval(decompteur).
Also be sure to reset the idTemps with idTemps.innerHTML = 20. Then I don't really understand... Why would you clear the interval then rebuild the same again when you can just set the idTemps.innerHTML so your interval will use the 20 for temps at the next iteration ?
PS: ça fait plaisir de voir un peu de français sur stack :)
You should rewrite your code this way :
function rage() {
var i = document.getElementsByName("msg")[6];
var message = document.getElementById("message");
const affichemsg = document.querySelector("msg");
for (i = 0; i < 1; i++) {
message.innerHTML += "Es-tu près ";
}
}
setInterval(rage, 350);
var decompteur = setInterval(msg, 1000);
function msg() {
var idTemps = document.getElementById("temps");
var temps = parseInt(idTemps.innerHTML) - 1;
idTemps.innerHTML = temps;
if (--temps == 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
idTemps.innerHTML = "20";
}
}
// when you need to, stop decompteur with :
// clearInterval(decompteur);
.titre2 {
width: 650px;
margin: auto;
text-align: center;
border-radius: 35px;
color: #000000;
background-color: #ff0000;
padding: 5px;
margin-bottom: 30px;
}
.bouton {
transition-duration: 0.4s;
border-width: 1px;
cursor: pointer;
}
.boutonOui {
background-color: rgb(234, 234, 234);
}
.boutonOui:hover {
background-color: rgb(177, 177, 177);
}
<div class="header">
<h1 class="titre2">Es-tu près</h1>
</div>
<button class="bouton boutonOui" id="boutonOui" onclick="window.location.href='jeu_educatifs2.html'">
Oui
</button>
<div id="temps">20</div>
<div id="message"></div>
<div id="msg" value="6"></div>
This keep as much of your code as possible, but as Rojo said, your code is very inefficent and there are a lot of things to improve.
Currently, your code is very inefficient. Rather than having your variable temps read from the DOM, you should have the variable update itself:
var temps = 20;
function msg() {
--temps;
}
setInterval(msg, 1000);
Second, you shouldn't be including var inside of that if statement:
if (countdown === 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
clearInterval(decompteur);
// msg(); // You don't need this
temps = 20;
decompteur = setInterval(msg, 1000); // I removed the var
}
Also, you had your variables mixed up (which I fixed)
function rage() {
var i = document.getElementsByName("msg")[6];
var message = document.getElementById("message");
const affichemsg = document.querySelector("msg");
for (i = 0; i < 1; i++) {
message.innerHTML += "Es-tu près ";
}
}
setInterval(rage, 350);
var decompteur = setInterval(msg, 1000);
var temps = 20;
var idTemps = document.getElementById("temps"); // I also moved this outside
function msg() {
--temps;
idTemps.innerHTML = temps;
if (temps === 0) {
alert("!!!!!ES-TU PRÈS!!!!!");
clearInterval(decompteur);
//msg(); //You don't need this
temps = 20;
decompteur = setInterval(msg, 1000);
}
}
.titre2 {
width: 650px;
margin: auto;
text-align: center;
border-radius: 35px;
color: #000000;
background-color: #ff0000;
padding: 5px;
margin-bottom: 30px;
}
.bouton {
transition-duration: 0.4s;
border-width: 1px;
cursor: pointer;
}
.boutonOui {
background-color: rgb(234, 234, 234);
}
.boutonOui:hover {
background-color: rgb(177, 177, 177);
}
<div class="header">
<h1 class="titre2">Es-tu près</h1>
</div>
<button
class="bouton boutonOui"
id="boutonOui"
onclick="window.location.href='jeu_educatifs2.html'"
>
Oui
</button>
<div id="temps">20</div>
<div id="message"></div>
<div id="msg" value="6"></div>
The following code prints the counter value each second and every 20 seconds it prints ALERT. Try to use a similar code for your example because your code is not very clear.
let counter = 0;
setInterval(() => {
counter++;
if (counter % 20 == 0) {
console.log("ALERT! ");
}
console.log("Counter Value: " + (counter % 20));
}, 1000);
hi so this is my js and the problem i have is my js works fine with the first div but it has no effect on the other divs, and i cant seem to find whats the problem. i guess i know what the problem is the only issue i have is i dont know how to solve it, i would appreciate it if u could help me
this is my js:
var incrementerHandle = document.querySelector('.incrementer .value');
var incrementValue = document.querySelector('.incrementer .value span');
var downButton = document.querySelector('.incrementer .down');
var upButton = document.querySelector('.incrementer .up');
var peek = document.querySelector('.incrementer .peek'); //Handle Bounds
var neutral = '50%';
var upper = 50;
var lower = 10; //Count Bounds
var count = 0;
var minCount = 0;
var maxCount = 100; //Timer for holding
var timer;
downButton.addEventListener('click', incrementDown);
upButton.addEventListener('click', incrementUp);
function dragEndHandler() {
peek.classList.remove('active');
checkPosition();
clearInterval(timer); //Return to neutral
incrementerHandle.style.left = neutral;
}
function timerTick() {
peek.classList.add('active');
checkPosition();
}
function checkPosition() {
if (dragger.position.x >= upper) {
incrementUp();
} else if (dragger.position.x <= lower) {
incrementDown();
}
}
function incrementUp() {
count++;
if (count > maxCount) {
count = maxCount;
}
updateValue();
}
function incrementDown() {
count--;
if (count < minCount) {
count = minCount;
}
updateValue();
}
function updateValue() {
incrementValue.innerHTML = count;
checkDisplay();
}
function checkDisplay() {
if (count <= minCount) {
downButton.classList.add('disabled');
} else if (count >= maxCount) {
upButton.classList.add('disabled');
} else {
downButton.classList.remove('disabled');
upButton.classList.remove('disabled');
}
}
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>
Based on your explanation on the comment line, you have multiple divs with class slider with similar implementation as the one you posted. In this case you would have to use querySelectorAll() which returns a node list, rather than using querSelector() which returns a single element. I have made a few more adjustments accordingly.
var downButton = document.querySelectorAll('.incrementer .down');
var upButton = document.querySelectorAll('.incrementer .up');
var peek = document.querySelector('.incrementer .peek'); //Handle Bounds
var neutral = '50%';
var upper = 50;
var lower = 10; //Count Bounds
var minCount = 0;
var maxCount = 100; //Timer for holding
var timer;
downButton.forEach( down => down.addEventListener('click', incrementDown));
upButton.forEach( up => up.addEventListener('click', incrementUp));
function dragEndHandler() {
peek.classList.remove('active');
checkPosition();
clearInterval(timer); //Return to neutral
incrementerHandle.style.left = neutral;
}
function timerTick() {
peek.classList.add('active');
checkPosition();
}
function checkPosition() {
if (dragger.position.x >= upper) {
incrementUp();
} else if (dragger.position.x <= lower) {
incrementDown();
}
}
function incrementUp(e) {
let element = e.target;
let count = 0;
if( element.classList.contains('mdc-button') ){
count = Number( element.nextElementSibling.firstElementChild.innerHTML ) + 1;
if (count > maxCount) {
count = maxCount;
}
element.nextElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element);
}
else {
count = Number( element.parentElement.nextElementSibling.firstElementChild.innerHTML ) + 1;
if (count > maxCount) {
count = maxCount;
}
element.parentElement.nextElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element.parentElement);
}
}
function incrementDown(e) {
let element = e.target;
let count = 0;
if( element.classList.contains('mdc-button') ){
count = Number( element.previousElementSibling.firstElementChild.innerHTML ) - 1;
if (count < minCount) {
count = minCount;
}
element.previousElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element);
}
else {
count = Number( element.parentElement.previousElementSibling.firstElementChild.innerHTML ) - 1;
if (count < minCount) {
count = minCount;
}
element.parentElement.previousElementSibling.firstElementChild.innerHTML = count;
checkDisplay(count, element.parentElement);
}
}
function checkDisplay(count, element) {
if (count <= minCount) {
element.classList.add('disabled');
} else if (count >= maxCount) {
element.classList.add('disabled');
} else {
element.classList.remove('disabled');
element.classList.remove('disabled');
}
}
#con{
border: 1px solid black;
padding: 10px;
width: 65%;
margin: 0 auto;
display: flex;
flex-direction: column;
justify-content: space-around;
text-align: center;
}
#con1{
border: 1px solid black;
flex-wrap: wrap;
display: flex;
flex-direction: row;
justify-content: space-around;
padding: 5px;
}
button{
background-color: #4CAF50; /* Green */
border: none;
color: white;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
}
select{
margin-top: 20px;
}
.redbu{
background-color: red;
}
.bluebu{
background-color: royalblue;
}
.greenbu{
background-color: #4CAF50;
}
.yellowbu{
background-color: yellow;
}
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>
<div class="slider">
<div class="incrementer">
<button class="mdc-button mdc-button--raised up">
<span class="mdc-button__ripple">+</span>
</button>
<button class="value">
<span>0</span>
</button>
<button class="mdc-button mdc-button--raised down">
<span class="mdc-button__ripple">-</span>
</button>
</div>
</div>
I have three classes box with randomly selected image and from array items, there is a square box002 at right lower portion, this can be drag and droppped to any of three box if it find match the box will dissappear . likwise three box will dissappear.
then a class bodyblue is added to body with backgroundImage named middle bg is added to body for 10 seconds . after again 3 box appear for drag and drop.
in the second level after this three boxes are dragged&dropped and deleted, when bodyblue is added to body the backgroundImage middle bg is not appearing in for 10 seconds.
How to add bodyblue backgroundImage to body using jquery in second level and third level?
var array2 = [];
var arraycart = [];
var disparray = [];
var bg = [];
var dataURL;
var timeOut;
counter = 0;
var items = [{
label: '1',url: 'https://via.placeholder.com/150x150.jpg?text=image1'},
{label: '2',url:'https://via.placeholder.com/150x150.jpg?text=image2'},
{label: '3',url:'https://via.placeholder.com/150x150.jpg?text=image3'},
{label: '4',url:'https://via.placeholder.com/150x150.jpg?text=image4'},
{label: '5',url:'https://via.placeholder.com/150x150.jpg?text=image5'},
{label: '6',url:'https://via.placeholder.com/150x150.jpg?text=image6'},
{label: '7',url:'https://via.placeholder.com/150x150.jpg?text=image7'},
{label: '8',url:'https://via.placeholder.com/150x150.jpg?text=image8'},
{label: '9',url:'https://via.placeholder.com/150x150.jpg?text=image9'},
{label:'10',url:'https://via.placeholder.com/150x150.jpg?text=image10'}
];
var notes = ['https://via.placeholder.com/150x150.jpg?text=image1',
'https://via.placeholder.com/150x150.jpg?text=image2',
'https://via.placeholder.com/150x150.jpg?text=image3',
'https://via.placeholder.com/150x150.jpg?text=image4',
'https://via.placeholder.com/150x150.jpg?text=image5',
'https://via.placeholder.com/150x150.jpg?text=image6',
'https://via.placeholder.com/150x150.jpg?text=image7',
'https://via.placeholder.com/150x150.jpg?text=image8',
'https://via.placeholder.com/150x150.jpg?text=image9',
'https://via.placeholder.com/150x150.jpg?text=image10'
];
var tempimages = [];
var notesselected = [];
array2 = items.slice();
var item;
//----------------------------------------------change backgroundImage----------------------------------------------------------
function changemainbackground() {
debugger;
var c = document.getElementById('main');
var img = document.getElementById('main'),
style = img.currentStyle || window.getComputedStyle(img, false),
bi = style.backgroundImage.slice(4, -1).replace(/"/g, "");
// Display the url to the user
//console.log('Image URL: ' + bi);
bodycontents = document.getElementById('main');
if (counter >= 0) {
bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
d = bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
//console.log(d);
}
counter++;
//console.log("counter is"+counter);
//console.log(bodycontents);
//console.log(d);
}
//--------------------------^^^^^change backgroundImage end here^^^^^^^--------------------------------------------------------
//----------------------------------------------hiddenImage------------------------------------------------------------------------
hiddenimgnumber = 0;
var images = ['https://picsum.photos/200/300', 'https://picsum.photos/200/300', 'https://picsum.photos/200/300'];
//var bg=['https://via.placeholder.com/150x150.jpg?text=image1','https://via.placeholder.com/150x150.jpg?text=image2'];
var bg = ['https://picsum.photos/200/300?image=2', 'https://picsum.photos/200/300?image=3', 'https://picsum.photos/200/300?image=4'];
var refreshIntervalId = setInterval(function() {
image = document.getElementById('hiddenimageid');
image.src = images[hiddenimgnumber];
}, 1)
function hiddenimage() {
clearInterval(refreshIntervalId);
image = document.getElementById('hiddenimageid');
image.src = images[hiddenimgnumber];
//console.log(hiddenimgnumber);
hiddenimgnumber++;
}
//-------------------------------------------------^^^hidden Image ends^^^------------------------------------------------------
window.onload = function() {}
function rvalue() {
elements = document.getElementsByClassName("box");
for (var i = 0; i < elements.length; i++) {
//debugger;
elements[i].style.border = "2px solid #c57232 ";
elements[i].style.borderBottom = "5px solid #c57232 ";
//object.style.borderRadius = "1-4 length|% / 1-4 length|%|initial|inherit"
}
ptags = document.querySelectorAll('[name="values"]');
boxtags = document.getElementsByClassName("box");
//if array length is 0 then we need to identify the game as completed
if (array2.length === 0) {
alert('Game completed');
return;
}
for (var index = 0; index < 3; index++) {
randomIndex = Math.floor(Math.random() * array2.length)
item = array2[randomIndex];
array2.splice(randomIndex, 1);
try {
//ptags[index].style.visibility = "visible";
//ptags[index].textContent = "RS."+item.label;
ptags[index].dataset.itemLabel = item.label;
//using label as an identity
tempimages.push({
data: item,
label: item.label
});
notesselected.push({
data: item.url,
label: item.label
});
boxtags[index].style.backgroundImage = 'url(' + item.url + ')';
} catch (err) {
// console.log('Exception');
}
}
var tlen = tempimages.length;
}
function displayAllImages() {
try {
if (tempimages.length == 0) {
rvalue();
}
if (tempimages.length === 0) {
image = document.getElementById('slide');
image.style.display = 'none';
return;
}
// getting random item from the available items
var arr2 = tempimages;
item = arr2[Math.floor(Math.random() * arr2.length)]
image = document.getElementById('slide');
//getting notes item
//console.log(item);
///////console.log(item.label);
var dataURL = notes.filter(a => a.indexOf("?text=" + item.label) > 0)[0];
//var dataURL =item.url;
//var dataURL = item.label;
console.log(dataURL);
image.src = dataURL;
image.dataset.itemLabel = item.label;
} catch (err) {
//console.log(err.message);
}
};
$(function() {
displayAllImages();
});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var x = document.getElementById("slide").dataset.itemLabel;
var y = ev.target.dataset.itemLabel;
//add improvisation box drag is valid
if (ev.target.tagName === "DIV") {
y = ev.target.children[0].dataset.itemLabel;
}
//console.log(x);
//console.log(y);
if (x == y) {
ev.currentTarget.style.backgroundColor = 'initial';
ev.currentTarget.style.backgroundImage = 'initial';
ev.currentTarget.style.border = 'initial';
var pParagraph = ev.currentTarget.firstElementChild;
pParagraph.style.visibility = "hidden";
item = this.item;
tempimages = tempimages.filter(a => a.label !== item.label);
if (tempimages.length == 0) {
rvalue();
hiddenimage();
animateCongrat();
}
displayAllImages();
} else {
}
}
//----------------------------->>>animate congarat starts here-------------------------------------------------------------
var timeOut;
function animateCongrat() {
//debugger;
$('.congrats').show();
clearTimeout(timeOut);
addBlueBody();
hideCongratAndBlueBody();
}
function addBlueBody() {
$("html").css("background-color", " #070755 ");
$('body').addClass('bodyblue')
//console.log(url);
$('#container').hide();
$('#2container').hide();
$('#3container').hide();
$('#2').hide();
$('.completed').hide();
}
function hideCongratAndBlueBody() {
timeOut = setTimeout(() => {
$('.congrats').hide();
$("html").css("background-color", "");
$('body').removeClass('bodyblue')
$('#container').show();
$('#2container').show();
$('#3container').show();
$('#2').show();
$('.completed').hide();
changemainbackground();
}, 10000);
}
//----------------------------->>>animate congarat ends here-------------------------------------------------------------
body {
overflow: hidden;
}
.dashed {
border: 2px dashed #999 !important;
}
.bodyblue {
background-image: url(https://via.placeholder.com/1000x600?text=Middle+bg);
height: 100vh;
width: 100vw;
}
ul {
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
}
.box {
width: calc(33.3% - 4px);
border-radius: 5px;
border: #000 border-color: #e6e600;
margin: -2px;
background-color: #99ffff;
height: 16vh;
display: inline-flex;
align-items: center;
justify-content: center;
background-repeat: no-repeat;
background-size: cover;
cursor: pointer;
}
.box002 {
position: absolute;
top: 40.3vh;
left: 50.98vw;
cursor: pointer;
border: 2px solid black;
}
.box002 img {
width: 15.0vw;
height: 15.0vh;
border-radius: 0%;
}
#container {
white-space: nowrap;
border: px solid #CC0000;
}
.containerr {
border: px solid #FF3399;
}
.pic {
background-size: 100% 100%;
}
.container2 {
width: 29.0vw;
position: fixed;
top: 23.9vh;
left: 19.2vw;
}
body {
background-image: url(https://picsum.photos/200/300?image=0);
background-size: 100vw 100vh;
}
.reset img:hover {
opacity: 1
}
.hiddenimage {
position: absolute;
top: 4.3vh;
left: 50vw;
cursor: pointer;
}
.hiddenimage img {
width: 10.3vw;
height: 10.5vh;
border-radius: 15%;
}
.hand {
position: absolute;
top: 45.3vh;
left: 17vw;
cursor: pointer;
}
.hand img {
width: 25.3vw;
height: 25.5vh;
border-radius: 0%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container2">
<div class="containerr">
<div class="pic" id="content">
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10" style="">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
</div>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" border="rounded" />
</div>
<div class="congrats">
<div class="hiddenimage" style="display:none;">
<img src="" id="hiddenimageid" />
</div>
</div>
I have three class boxes with a randomly selected image and from array items. There is a square box002 at right lower portion, this can be drag and dropped to any of three boxes. If it finds a match, the box will disappear, likewise, box three will disappear.
Then a class named bodyblue is added to the body with a backgroundImage named middle bg is added to body for 10 seconds. After again box three appears for drag and drop.
The problem I am having is:
In the second level after three boxes are dragged & dropped and deleted, when bodyblue is added to body the backgroundImage middle bg is not appearing in for 10 seconds.
How do I add bodyblue backgroundImage to body using jquery in second level and third level?
var array2 = [];
var arraycart = [];
var disparray = [];
var bg = [];
var dataURL;
var timeOut;
counter = 0;
var items = [{
label: '1',url: 'https://via.placeholder.com/150x150.jpg?text=image1'},
{label: '2',url:'https://via.placeholder.com/150x150.jpg?text=image2'},
{label: '3',url:'https://via.placeholder.com/150x150.jpg?text=image3'},
{label: '4',url:'https://via.placeholder.com/150x150.jpg?text=image4'},
{label: '5',url:'https://via.placeholder.com/150x150.jpg?text=image5'},
{label: '6',url:'https://via.placeholder.com/150x150.jpg?text=image6'},
{label: '7',url:'https://via.placeholder.com/150x150.jpg?text=image7'},
{label: '8',url:'https://via.placeholder.com/150x150.jpg?text=image8'},
{label: '9',url:'https://via.placeholder.com/150x150.jpg?text=image9'},
{label:'10',url:'https://via.placeholder.com/150x150.jpg?text=image10'}
];
var notes = ['https://via.placeholder.com/150x150.jpg?text=image1',
'https://via.placeholder.com/150x150.jpg?text=image2',
'https://via.placeholder.com/150x150.jpg?text=image3',
'https://via.placeholder.com/150x150.jpg?text=image4',
'https://via.placeholder.com/150x150.jpg?text=image5',
'https://via.placeholder.com/150x150.jpg?text=image6',
'https://via.placeholder.com/150x150.jpg?text=image7',
'https://via.placeholder.com/150x150.jpg?text=image8',
'https://via.placeholder.com/150x150.jpg?text=image9',
'https://via.placeholder.com/150x150.jpg?text=image10'
];
var tempimages = [];
var notesselected = [];
array2 = items.slice();
var item;
//change backgroundImage
function changemainbackground() {
bodycontents = document.getElementById('main');
if (counter >= 0) {
bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
d = bodycontents.style.backgroundImage = 'url(' + bg[counter] + ')';
}
counter++;
}
hiddenimgnumber = 0;
var images = ['https://picsum.photos/200/300', 'https://picsum.photos/200/300', 'https://picsum.photos/200/300'];
//var bg=['https://via.placeholder.com/150x150.jpg?text=image1','https://via.placeholder.com/150x150.jpg?text=image2'];
var bg = ['https://picsum.photos/200/300?image=2', 'https://picsum.photos/200/300?image=3', 'https://picsum.photos/200/300?image=4'];
var refreshIntervalId = setInterval(function() {
image = document.getElementById('hiddenimageid');
image.src = images[hiddenimgnumber];
}, 1)
function hiddenimage() {
clearInterval(refreshIntervalId);
image = document.getElementById('hiddenimageid');
image.src = images[hiddenimgnumber];
//console.log(hiddenimgnumber);
hiddenimgnumber++;
}
window.onload = function() {}
function rvalue() {
elements = document.getElementsByClassName("box");
for (var i = 0; i < elements.length; i++) {
//debugger;
elements[i].style.border = "2px solid #c57232 ";
elements[i].style.borderBottom = "5px solid #c57232 ";
//object.style.borderRadius = "1-4 length|% / 1-4 length|%|initial|inherit"
}
ptags = document.querySelectorAll('[name="values"]');
boxtags = document.getElementsByClassName("box");
if (array2.length === 0) {
alert('Game completed');
return;
}
for (var index = 0; index < 3; index++) {
randomIndex = Math.floor(Math.random() * array2.length)
item = array2[randomIndex];
array2.splice(randomIndex, 1);
try {
//ptags[index].style.visibility = "visible";
//ptags[index].textContent = "RS."+item.label;
ptags[index].dataset.itemLabel = item.label;
//using label as an identity
tempimages.push({
data: item,
label: item.label
});
notesselected.push({
data: item.url,
label: item.label
});
boxtags[index].style.backgroundImage = 'url(' + item.url + ')';
} catch (err) {
// console.log('Exception');
}
}
var tlen = tempimages.length;
}
function displayAllImages() {
try {
if (tempimages.length == 0) {
rvalue();
}
if (tempimages.length === 0) {
image = document.getElementById('slide');
image.style.display = 'none';
return;
}
var arr2 = tempimages;
item = arr2[Math.floor(Math.random() * arr2.length)]
image = document.getElementById('slide');
//getting notes item
//console.log(item);
///////console.log(item.label);
var dataURL = notes.filter(a => a.indexOf("?text=" + item.label) > 0)[0];
//var dataURL =item.url;
//var dataURL = item.label;
console.log(dataURL);
image.src = dataURL;
image.dataset.itemLabel = item.label;
} catch (err) {
}
};
$(function() {
displayAllImages();
});
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("Text", ev.target.id);
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("Text");
var x = document.getElementById("slide").dataset.itemLabel;
var y = ev.target.dataset.itemLabel;
if (ev.target.tagName === "DIV") {
y = ev.target.children[0].dataset.itemLabel;
}
if (x == y) {
ev.currentTarget.style.backgroundColor = 'initial';
ev.currentTarget.style.backgroundImage = 'initial';
ev.currentTarget.style.border = 'initial';
var pParagraph = ev.currentTarget.firstElementChild;
pParagraph.style.visibility = "hidden";
item = this.item;
tempimages = tempimages.filter(a => a.label !== item.label);
if (tempimages.length == 0) {
rvalue();
hiddenimage();
animateCongrat();
}
displayAllImages();
} else {
}
}
//animate congarat starts here
var timeOut;
function animateCongrat() {
$('.congrats').show();
clearTimeout(timeOut);
addBlueBody();
hideCongratAndBlueBody();
}
function addBlueBody() {
$("html").css("background-color", " #070755 ");
$('body').addClass('bodyblue')
$('#container').hide();
$('#2container').hide();
$('#3container').hide();
$('#2').hide();
$('.completed').hide();
}
function hideCongratAndBlueBody() {
timeOut = setTimeout(() => {
$('.congrats').hide();
$("html").css("background-color", "");
$('body').removeClass('bodyblue')
$('#container').show();
$('#2container').show();
$('#3container').show();
$('#2').show();
$('.completed').hide();
changemainbackground();
}, 5000);
}
body {
overflow: hidden;
}
.dashed {
border: 2px dashed #999 !important;
}
.bodyblue {
background-image: url(https://via.placeholder.com/1000x600?text=Middle+bg);
height: 100vh;
width: 100vw;
}
ul {
-moz-border-radius: 50%;
-webkit-border-radius: 50%;
}
.box {
width: calc(33.3% - 4px);
border-radius: 5px;
border: #000 border-color: #e6e600;
margin: -2px;
background-color: #99ffff;
height: 16vh;
display: inline-flex;
align-items: center;
justify-content: center;
background-repeat: no-repeat;
background-size: cover;
cursor: pointer;
}
.box002 {
position: absolute;
top: 30.3vh;
left: 50.98vw;
cursor: pointer;
border: 2px solid white;
}
.box002 img {
width: 15.0vw;
height: 15.0vh;
border-radius: 0%;
}
#container {
white-space: nowrap;
border: px solid #CC0000;
}
.containerr {
border: px solid #FF3399;
}
.pic {
background-size: 100% 100%;
}
.container2 {
width: 29.0vw;
position: fixed;
top: 10.9vh;
left: 19.2vw;
}
body {
background-image: url(https://picsum.photos/200/300?image=0);
background-size: 100vw 100vh;
}
.reset img:hover {
opacity: 1
}
.hiddenimage {
position: absolute;
top: 4.3vh;
left: 50vw;
cursor: pointer;
}
.hiddenimage img {
width: 10.3vw;
height: 10.5vh;
border-radius: 15%;
}
.hand {
position: absolute;
top: 45.3vh;
left: 17vw;
cursor: pointer;
}
.hand img {
width: 25.3vw;
height: 25.5vh;
border-radius: 0%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body id="main">
<div class="container2">
<div class="containerr">
<div class="pic" id="content">
<div id="container">
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="10" style="">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="11">
<p name="values"></p>
</div>
<div class="box" ondrop="drop(event)" ondragover="allowDrop(event)" id="12">
<p name="values"></p>
</div>
</div>
</div>
</div>
</div>
<div class="box002" draggable="true" ondragstart="drag(event)" id="2">
<img src="" draggable="true" id="slide" border="rounded" />
</div>
<div class="congrats">
<div class="hiddenimage" style="display:none;">
<img src="" id="hiddenimageid" />
</div>
</div>
</body>
Hello guys I hope you can help me with JavaScript, I'm trying to itarate over some divs, the issue is that when I iterate sometimes a div never change to the other divs, it suppose to be infinite, I will recive thousands of different divs with different height and it should create an other div container in the case it does not fits but I can not achieve it work's, I'm using Vanilla JavaScript because I'm lerning JavaScript Regards.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
.big_container{
height: 600px;
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items{
background-color: gray;
height: 50px;
}
.new_container{
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
float: left;
margin-left: 5px;
}
</style>
</head>
<body>
<div class="big_container">
<div class="items">1</div>
<div class="items">2</div>
<div class="items">3</div>
<div class="items">4</div>
<div class="items">5</div>
<div class="items">6</div>
<div class="items">7</div>
<div class="items">8</div>
<div class="items">9</div>
<div class="items">10</div>
<div class="items">11</div>
<div class="items">12</div>
<div class="items">13</div>
</div>
<div class="new_container">
</div>
</body>
<script>
number = 0
sum = 0
new_container = document.getElementsByClassName('new_container')[number].offsetHeight
divs = document.getElementsByClassName('items')
for ( var i = 0; i < divs.length; i++ ){
sum += this.document.getElementsByClassName( 'items' )[0].offsetHeight
if ( sum <= new_container ){
console.log(sum, "yes")
document.getElementsByClassName("new_container")[number].appendChild( this.document.getElementsByClassName( 'items' )[0] )
} else {
sum = 0
console.log(sum, "NO entra")
nuevo_contenedor = document.createElement('div'); // Creo un contenedor
nuevo_contenedor.className = "new_container";
nuevo_contenedor.setAttribute("style", "background-color: red;");
document.body.appendChild(nuevo_contenedor)
number += + 1
}
}
</script>
</html>
I really apreciate a hand.
I know that I'm late, but there is my approach how this can be done.
// generate items with different height
function generateItems(count) {
const arr = [];
for (let i = 0; i < count; i++) {
const div = document.createElement("DIV");
const height = Math.floor((Math.random() * 100) + 10);
div.setAttribute("style", `height: ${height}px`);
div.setAttribute("class", "items");
const t = document.createTextNode(i + 1);
div.appendChild(t);
arr.push(div);
}
return arr;
}
function createNewContainer(height) {
const new_container = document.createElement("DIV")
new_container.setAttribute("class", "new_container");
new_container.setAttribute("style", `height: ${height}px`)
document.body.appendChild(new_container);
return new_container;
}
function breakFrom(sourceContainerId, newContainerHeight) {
const srcContainer = document.getElementById(sourceContainerId);
const items = srcContainer.childNodes;
let new_container = createNewContainer(newContainerHeight);
let sumHeight = 0;
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (item.offsetHeight > newContainerHeight) {
// stop!!! this item too big to fill into new container
throw new Error("Item too big.");
}
if (sumHeight + item.offsetHeight < newContainerHeight) {
// add item to new container
sumHeight += item.offsetHeight;
new_container.appendChild(item.cloneNode(true));
} else {
// create new container
new_container = createNewContainer(newContainerHeight);
new_container.appendChild(item.cloneNode(true));
// don't forget to set sumHeight)
sumHeight = item.offsetHeight;
}
}
// if you want to remove items from big_container
// for (let i = items.length - 1; i >= 0; i--) {
// srcContainer.removeChild(items[i]);
// }
}
// create big container with divs
const big_container = document.getElementById("big_container");
const items = generateItems(13);
items.forEach((div, index) => {
big_container.appendChild(div);
});
breakFrom("big_container", 300);
#big_container {
width: 150px;
background-color: #f1f1f1;
float: left;
}
.items {
background-color: gray;
border: 1px solid #000000;
text-align: center;
}
.new_container {
margin-bottom: 10px;
height: 300px;
width: 150px;
background-color: red;
border: 1px solid red;
float: left;
margin-left: 5px;
}
<div id="big_container"></div>
This example gives you the ability to play with divs of random height. Hope, this will help you.