add div using appenChild and decrease div using removeChild - javascript

I want to make fractal tree and if i press left click i suppossed to be add new div and if i press right click it supposed to be decrease div, but the left click function didn't work, its supposed to be recursive but it just add one div and if i press left click again nothing happen and the right click also didn't work, all of the div disappear. this is my code
<head>
<style type="text/css">
div {
position: absolute;
background-color: #e21d27;
opacity: 0.8;
transition: 2s;
}
div#start {
width: 100px;
height: 100px;
transform: translate(300%, 300%);
}
div div {
width: 100%;
height: 100%;
}
div div:nth-child(1) {
transform: translate(-42%, -105%) rotate(-37deg) scale(0.8, 0.8);
}
div div:nth-child(2) {
transform: translate(55%, -91%) rotate(53deg) scale(0.6, 0.6) ;
}
div:hover {
transition: 1s;
opacity: 1;
}
</style>
</head>
<body>
<div id="start"></div>
<script>
var coba =27;
var leftClick = document.getElementById("start");
var rightClick = document.getElementById("start");
leftClick.onclick = function(){
for ( var i = 0; i< coba; i++ ) {
var di = document.createElement('div');
leftClick.appendChild(di);
}
}
rightClick.oncontextmenu = function(){
for ( var i = 0; i< coba; i++ ) {
var removedi = document.getElementById("start");;
removedi.parentNode.removeChild(removedi);
}
}
</script>
</body>
thank you so much for your help

Your rightclick function is removing the whole "start" div. removedi is set to that div and then you are calling removeChild on its parent, causing it to be removed. That's probably why everything is getting removed when you right click. Instead, you should remove child nodes of the start div.
You probably want something like:
var start = document.getElementById('start');
for (var i = 0; i < start.childNodes.length; i++) {
var child = start.childNodes[i];
start.removeChild(child);
}
I'm not sure why your left-click handler is not doing what you want.

Related

How to change the properties of a sticky up arrow button based on its position?

I have a sticky up arrow image for my webpage as follows:
HTML:
<img src = "images/sticky-btn-light.png" id = "myBtn" alt = "sticky-up-button">
And CSS:
#myBtn {
visibility: hidden;
position: fixed;
bottom: 50px;
right: 30px;
z-index: 99;
cursor: pointer;
padding: 15px;
border-radius: 10px;
width: 5%;
opacity: 0.5 ;
}
The button disappears when the user scrolls down and appears when the user scrolls up based on this JS code.
window.onscroll = function(e) {
console.log(this.oldScroll > this.scrollY);
if((this.scrollY == 0) || (this.oldScroll < this.scrollY) ){
document.getElementById('myBtn').style.visibility = 'hidden';
}
else if(this.oldScroll > this.scrollY){
document.getElementById('myBtn').style.visibility = 'visible';
}
this.oldScroll = this.scrollY;
}
Now, I want to change the color of the button based on its changing position on the screen. As I scroll the page, the sticky button will be in different sections as below.
If the sticky button is in Section A, it should be red. And if it is in Section B, it should be blue. Please note that it's the page that is moving, not the button. The button is in a fixed position.
For this, I need the id of the section in which the sticky button is overlapping at any given moment. Is there any way to get that information through JavaScript?
PS: I have adjusted the details to make things more clear. It's the page that is moving. So, if I use Element.getBoundingClientRect() for #myBtn, will I not get the same top/y values for that element wherever I scroll on the page?
You can use element.getBoundingClientRect() to get the x,y of the top left corner and the x,y of the bottom right corner of a element.
var arrow = document.getElementById('myBtn');
var arrowRect = arrow.getBoundingClientRect();
console.log(arrowRect.top, arrowRect.right, arrowRect.bottom, arrowRect.left);
var section = document.getElementById('section1');
var sectionRect = section.getBoundingClientRect();
console.log(sectionRect.top, sectionRect.right, sectionRect.bottom, sectionRect.left);
Then you can check collisions with the arrow and the section. In your case the x-axis doesn't matter:
// This checks if the arrow is touching the section
( arrowRect.bottom > sectionRect.top && arrowRect.top < sectionRect.bottom )
// This checks if the arrow isn't touching the section, then inverts it (faster)
!( arrowRect.bottom < sectionRect.top || arrowRect.top > sectionRect.bottom )
Here, I did an example for you to test and implement.
this will also help understand getBoundingClientRect even with fixed position
var arrow= document.getElementById('myBtn');
window.onscroll = function(e) {
var arrowBound = arrow.getBoundingClientRect();
var divs = document.querySelectorAll(".container > div");
divs.forEach(function(item){
var divBound = item.getBoundingClientRect();
var color= item.getAttribute("arrowColor");
if ( arrowBound.bottom > divBound.top && arrowBound.top < divBound.bottom )
{
arrow.style.borderTopColor = color
}
})
}
#myBtn {
position: fixed;
top: 10px;
left:270px;
z-index: 99;
cursor: pointer;
width: 0;
height: 0;
border-left: 20px solid transparent;
border-right: 20px solid transparent;
border-top: 20px solid #f00;
}
.container{
width:300px;
height:800px;
z-index: 81;
}
.container > div {
width:300px;
height:100px;
border:1px solid black;
}
<div class="container">
<a id = "myBtn" href = "#navbar-scroll"></a>
<div arrowColor="red"> box red </div>
<div arrowColor="blue"> box blue </div>
<div arrowColor="green"> box green </div>
</div>
You can get coords of a html element with getBoundingClientRect() method, call this function and you'll get the Y coords of element (pixels), then you can use an if conditional
function getCoords(elem) {
let box = elem.getBoundingClientRect();
let body = document.body;
let docEl = document.documentElement;
let scrollTop = window.pageYOffset || docEl.scrollTop || body.scrollTop;
let clientTop = docEl.clientTop || body.clientTop || 0;
return Math.round(box.top + scrollTop - clientTop);
}
if(getCoords(elem) > 100){
elem.className = 'your_class_name'
}
.your_class_name{
color: red;
}

how to make a div grow to cover a paragraph in javascript with transition?

I am trying to make a transition with a div that should grow and overlap a text.
Here are my codes
const box = document.querySelector("#box");
const mybutt = document.querySelector("#mybutt");
mybutt.addEventListener("click", transitionfunction);
function transitionfunction() {
if(box.style.height != "100px"){
box.style.height = "100px";
box.style.transition = "2s";
}
else {
box.style.height = "50px";
box.style.transition = "2s";
}
}
#box {
background: red;
height: 50px;
width: 50px;
}
#para {
postion: fixed;
}
<div id="parentdiv">
<div id="box"></div>
<p id="para">Help</p>
</div>
<button id="mybutt">click</button>
At the moment, on the click of the button, both the button and the paragraph para move down, I want them to be fixed and I want the div, #box to cover the para but its not working. I tried putting it to fixed but doesnt work. And on the click on the button again, it should reveal the text again.
If you use position: fixed;, you should manually set the top property.
To make a div overlay some text, use z-index
const box = document.querySelector("#box");
const mybutt = document.querySelector("#mybutt");
mybutt.addEventListener("click", transitionfunction);
function transitionfunction() {
if (box.style.height != "100px"){
box.style.height = "100px";
box.style.transition = "2s";
} else {
box.style.height = "50px";
box.style.transition = "2s";
}
}
#mybutt {
position: fixed;
top: 120px;
}
#box {
background: red;
position: fixed;
height: 50px;
width: 50px;
z-index: 2;
}
#para {
position: fixed;
z-index: 1;
top: 60px;
}
<div id="parentdiv">
<div id="box"></div>
<p id="para">Help</p>
</div>
<button id="mybutt">click</button>
Firstly, you spelled "position" wrong for #para. Change it to:
#para {
position: absolute;
top: 10%;
}
This will keep the paragraph positioned in one spot; it won't move.
Fixed will work, although you might want to use 'absolute' instead if you want it to anchored to it's parent instead of the window itself.
Also, 'position' is misspelled; not sure if it is in your testing code.
The 'top' property has to be set for the element to know where to anchor itself, the 'position' property is what to anchor to.
HTML
<div id="parentdiv">
<div id="box"></div>
<p id="para">Help</p>
</div>
</div>
<button id="mybutt">click</button>
CSS
<style>
#box {
background: red;
height: 50px;
width: 50px;
}
#para {
position: absolute;
top:70;
}
</style>
*You also might want to move '#para' outside '#parentdiv', but it depends what you'll trying to ultimately do, it does work inside too.
Added:
To include an alert at 75px, you have to use a function that gives you more granular control(as far as I know at least). This is one solution:
<script>
const box = document.querySelector("#box");
const mybutt = document.querySelector("#mybutt");
mybutt.addEventListener("click", transitionfunction);
var intHeight = $("#box").css("height").split("p")[0];
function transitionfunction() {
if(intHeight < 100) {
intHeight++;
$("#box").css("height", intHeight + "px");
if (intHeight===76)
alert("75px!")
requestAnimationFrame(transitionfunction);
}
intHeight = $("#box").css("height").split("p")[0];
mybutt.addEventListener("click", revtransitionfunction);
mybutt.removeEventListener("click", transitionfunction);
}
function revtransitionfunction() {
if(intHeight >= 50) {
intHeight--;
$("#box").css("height", intHeight + "px");
if (intHeight===74)
alert("75px!")
requestAnimationFrame(revtransitionfunction);
}
intHeight = $("#box").css("height").split("p")[0];
mybutt.addEventListener("click", transitionfunction);
mybutt.removeEventListener("click", revtransitionfunction);
}

Create dynamic Rectangle collection in html using js

Hello All I am a beginner in html and js, and I am trying to create a webpage containing a rectangle collection in which when a new rectangle is created is placed beside the previous rectangle.
I have created a div element and trying to add newly created div (rectangle shape with background color different based on condition), but I am not able to get the desired result.
<html>
<head>
<title>parkIn</title>
<meta charset="utf-8" />
</head>
<style>
.ParkSlots {
border: solid 1px;
width: 60%;
height: 400px;
top: 50%;
left: 50%;
position: fixed;
transform: translate(-50%, -50%);
display: inline;
}
.row:before,
.row:after {
content: "";
display: table;
clear: both;
}
.col-1 {
width: 15%;
margin-left: 10px;
height: 350px;
padding: 2px;
}
</style>
<body onload="viewCreate()">
<div class="ParkSlots">
<div class="row" id="content">
</div>
</div>
</body>
<script language="javascript">
function viewCreate() {
for (int i = 0; i < 5; i++) {
if (i % 2 == 0) {
createGreenBox();
} else {
createRedBox();
}
}
}
function createRedBox() {
var = document.createElement('div');
div.className = 'col-1';
div.style.backgroundColor = 'red';
document.getElementById('content').appendChild(div);
}
function createGreenBox() {
var = document.createElement('div');
div.className = 'col-1';
div.style.backgroundColor = 'lightgreen';
document.getElementById('content').appendChild(div);
}
</script>
</html>
I want an output that looks something like this:
Just in glancing at your code, I see at least two typos:
for (int i = 0; i < 5; i++) { - in JS, int is not used in this way. Use var i = 0...
var = document.createElement('div'); - you're missing a variable name on this line in both create box functions. I assume, from the rest of the code you need var div = document.createElement('div');
The rest will be CSS. In your stylesheet you're applying the border to the outter most containing div, from you're example, you need to apply that to the .col-1 class. You'll also want to use display:inline-block on that class, and set widths and margins to play nicely with the border size. I took the liberty of creating a jsfiddle for you with my recommended changes.

How make a fade slideshow loop?

I am using javascript to change my css class background image every few seconds. It is working great the problem is it just stops after it shows the last image. Can anyone show me what to add to this code so that it will continuously loop itself?
$(window).load(function() {
$(document).ready(function() {
setInterval(fadeDivs, 5000); //call it every 2 seconds
function fadeDivs() {
var visibleDiv = $('.bckgnd:visible:first'); //find first visible div
visibleDiv.fadeOut(400, function() { //fade out first visible div
var allDivs = visibleDiv.parent().children(); //all divs to fade out / in
var nextDivIndex = (allDivs.index(visibleDiv) + 1) % allDivs.length; //index of next div that comes after visible div
var nextdiv = allDivs.eq(nextDivIndex); //find the next visible div
var lastDiv = $('.backgnd3');
var firstDiv = $('.backgnd1');
if (currentDiv != lastDiv) {
var nextdiv = allDivs.eq(nextDivIndex); //find the next visible div
} else {
var nextdiv = firstDiv; //the next div will be the first div, resulting in a loop
}
nextdiv.fadeIn(400); //fade it in
});
};
});
});
.backgnd1 {
width: 100%;
height: 452px;
background: url ('http://quaaoutlodge.com/sites/all/themes/marinelli/img/backgrounds/backgnd1.jpg');
background-size: cover;
background-repeat: no-repeat;
background-color: #000;
}
.backgnd2 {
width: 100%;
height: 452px;
background-image: url ('http://quaaoutlodge.com/sites/all/themes/marinelli/img/backgrounds/the_lodge.jpg');
background-size: cover;
background-repeat: no-repeat;
background-color: #000;
}
.backgnd3 {
width: 100%;
height: 452px;
background-image: url('http://quaaoutlodge.com/sites/all/themes/marinelli/img/backgrounds/getting_here.jpg');
background-size: cover;
background-repeat: no-repeat;
background-color: #000;
}
.index_roof_background {
background-color: #000;
width: 1600px;
height: 452px;
margin: 0px;
padding-top: 0px;
margin-left: auto;
margin-right: auto;
}
<div class="index_roof_background">
<div style="position:absolute; z-index: 2;display:block; background-color:#000;" class="bckgnd backgnd1"></div>
<div style="position:absolute; z-index: 2;display:none; background-color:#000;" class="bckgnd backgnd2"></div>
<div style="position:absolute; z-index: 2;display:none; background-color:#000;" class="bckgnd backgnd3"></div>
</div>
A better approach:
You don't need all those backgnd2 classes since you have only those DIVs inside a common parent.
Don't use inline styles! Use your stylesheet.
Don't use fixed width (px). Use % for responsive design.
2000*1331px images are
not suited for the web. Specially not for mobile devices. Care about
your user's bandwidth. When setting a background-image to cover you
don't need to worry about it being repeated.
Make your JS more flexible to element's indexes, count your elements using length.
Create a "current index counter", iterate over it increment it and
resetting using % (reminder).
For a better UX, allow the user to pause on hover.
Here's an eample:
jQuery(function($) { // DOM ready. $ alias in scope.
$('.gallery').each(function() {
var $gal = $(this),
$sli = $gal.find(">*"),
tot = $sli.length,
c = 0,
itv = null;
$sli.hide().eq(c).show(); // Hide all but first slide
function anim() {
c = ++c % tot; // increment/reset counter
$sli.fadeOut().eq(c).stop().fadeIn();
}
function play() {
itv = setInterval(anim, 3000);
}
function pause() {
clearInterval(itv);
}
$gal.hover(pause, play); // Pause on hover
play(); // Start loop
});
});
.gallery {
position: relative;
height: 200px;
}
.gallery>* {
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: none 50%;
background-size: cover;
}
<div class="gallery">
<div style="background-image:url(http://placehold.it/800x600/0bf?text=1)"></div>
<div style="background-image:url(http://placehold.it/800x600/f0b?text=2)"></div>
<div style="background-image:url(http://placehold.it/800x600/0fb?text=3)"></div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
First put the firstDiv, lastDiv in their own variables.
Then you will need something like this
if (currentDiv != lastDiv) {
var nextdiv = allDivs.eq(nextDivIndex); //find the next visible div
} else {
var nextdiv = firstDiv; //the next div will be the first div, resulting in a loop
}
nextdiv.fadeIn(400); //fade it in
Tell me if you need more help.
You need to use 2 timeouts to make it loop. A timeout only fires once. The FadeOutDivs function counts down, each time setting a timeout to call itself. Then at zero it fades sets a timeout the call fadeInDivs which start the whole cycle over.
I've got this running on codepen.
$(document).ready(function () {
var interval = 2000;
var fadeDuration = 400;
var allImages = $('.bckgnd');
var count = allImages.length - 1;
var imageCount = allImages.length;
setTimeout(fadeOutDivs, interval);
function fadeOutDivs() {
allImages.eq(count).fadeOut(fadeDuration);
console.log(count);
if (count > 1) {
count--;
setTimeout(fadeOutDivs, interval);
} else {
count = allImages.length - 1;
setTimeout(fadeInDivs, interval)
}
}
function fadeInDivs() {
allImages.fadeIn(fadeDuration);
setTimeout(fadeOutDivs, interval);
}
});

Implementing a loading spinning wheel in javascript

In my web site I need to pop up a dummy 'loading' spinning wheel when click a button and vanish after some time. It's just a dummy page. I would be much obliged if anyone can explain how to do such a thing. Can I do this with javascript or jQuery?
Thanx in advance
Have a div/image in the right place you need, hide it first time the page loaded. like
<input type="button" id="button"/>
<div id="load"><img src="http://jimpunk.net/Loading/wp-content/uploads/loading1.gif"/>
</div>
and in your jquery, set a handler for the click event of button to show or hide the div
$(document).ready(function(){
$('#button').click(function(){
$('#load').show();
setTimeout(function() {$('#load').hide()}, 2000);
});
});
setTimout can be used to hide the div after some time.
check the workign example here
you can do it by ajax or simply jquery.
here is the ajax way
$.ajax({
type: "POST",
data: serializedDataofthisform,
dataType: "html", /* or json */
url: "your url",
/* ajax magic here */
beforeSend: function() {
$('#loaderImg').show(); /*showing a div with spinning image */
},
/* after success */
success: function(response) {
/* simply hide the image */
$('#loaderImg').hide();
/* your code here */
}
});
html
<div id="loaderImg"><img src="path" alt=""/></div>
Javascript
by time out function :- setTimeout()
Here's another example that doesn't use an image.
// Author: Jared Goodwin
// showLoading() - Display loading wheel.
// removeLoading() - Remove loading wheel.
// Requires ECMAScript 6 (any modern browser).
function showLoading() {
if (document.getElementById("divLoadingFrame") != null) {
return;
}
var style = document.createElement("style");
style.id = "styleLoadingWindow";
style.innerHTML = `
.loading-frame {
position: fixed;
background-color: rgba(0, 0, 0, 0.8);
left: 0;
top: 0;
right: 0;
bottom: 0;
z-index: 4;
}
.loading-track {
height: 50px;
display: inline-block;
position: absolute;
top: calc(50% - 50px);
left: 50%;
}
.loading-dot {
height: 5px;
width: 5px;
background-color: white;
border-radius: 100%;
opacity: 0;
}
.loading-dot-animated {
animation-name: loading-dot-animated;
animation-direction: alternate;
animation-duration: .75s;
animation-iteration-count: infinite;
animation-timing-function: ease-in-out;
}
#keyframes loading-dot-animated {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
`
document.body.appendChild(style);
var frame = document.createElement("div");
frame.id = "divLoadingFrame";
frame.classList.add("loading-frame");
for (var i = 0; i < 10; i++) {
var track = document.createElement("div");
track.classList.add("loading-track");
var dot = document.createElement("div");
dot.classList.add("loading-dot");
track.style.transform = "rotate(" + String(i * 36) + "deg)";
track.appendChild(dot);
frame.appendChild(track);
}
document.body.appendChild(frame);
var wait = 0;
var dots = document.getElementsByClassName("loading-dot");
for (var i = 0; i < dots.length; i++) {
window.setTimeout(function(dot) {
dot.classList.add("loading-dot-animated");
}, wait, dots[i]);
wait += 150;
}
};
function removeLoading() {
document.body.removeChild(document.getElementById("divLoadingFrame"));
document.body.removeChild(document.getElementById("styleLoadingWindow"));
};
document.addEventListener('keydown', function(e) {
if (e.keyCode === 27) {
removeLoading();
}
}, false);
<html>
<button onclick="showLoading()">Click me</button>
<p>Press Escape to stop animation.</p>
</html>

Categories

Resources