CSS Absolute Positioning of Images - javascript

I was trying to position several images in a so they overlap with each other. I want to use absolute positioning, but for reason all of the images position themselves relative to the and not to each other. If I use s instead of images this works. It appears that, unlike s, images do not position themselves relative to other images but only to a , is that correct?
CSS
#container2 {
width: 340px;
height: 200px;
border: 1px solid black;
position: absolute;
top: 250px;
}
.playingcard {
width: 72px;
height: 100px;
position: absolute;
left: 0px;
}
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<div id=container2>
</div>
<script src=script.js></script>
</body>
</html>
JavaScript
const imageArray = ['/images/back/purple_back.png', '/images/back/red_back.png', '/images/back/yellow_back.png' ];
const container2 = document.getElementById('container2');
console.log(container2);
for (i = 0; i < imageArray.length; i++) {
const newImage = new Image();
newImage.src = imageArray[i];
newImage.className = 'playingcard';
imgArray = container2.getElementsByTagName('img');
console.log(imgArray.length);
if (imgArray.length == 0) {
container2.appendChild(newImage);
} else {
newImage.style.top = (i * 20) + 'px';
imgArray[imgArray.length - 1].appendChild(newImage);
}
}
Thanks
Denis

2 Observations
Your this code is never going to execute in a the for loop.
if (imgArray.length == 0) {
container2.appendChild(newImage);
}
You are pushing image in imageArray, so your structure will be like this
<container2>
<img src="src1">
<img src="src2">
<img src="src3">
</img>
</img>
</img>
</container2>
Here even if you use position absolute to each image will be absolute to its parent. so you will see overlapping images.
Replace your else condition with this (Remove if also)
else {
newImage.style.top = (i * 20) + 'px';
container2.appendChild(newImage); // ADD THIS
// imgArray[imgArray.length - 1].appendChild(newImage); // REMOVE THIS
}
Your structure now will be as you are expecting. You can play around with the CSS to get a view you want.

Your problem is that all img tags are nested within each other. Due to this, your top rule did not work. Example without condition if.
const imageArray = ['https://avatars.mds.yandex.net/get-pdb/2265897/d83bbab3-4bc4-42cc-8d62-a21b4c77ed72/s1200', 'https://64.img.avito.st/1280x960/4394790064.jpg', 'https://i.mycdn.me/i?r=AyH4iRPQ2q0otWIFepML2LxRUoA1zBVpY6nfGdB73g4vbw' ];
const container2 = document.getElementById('container2');
console.log(container2);
for (i=0; i<imageArray.length; i++) {
const newImage = new Image();
newImage.src = imageArray[i];
newImage.className = 'playingcard';
imgArray = container2.getElementsByTagName('img');
console.log(imgArray.length);
container2.appendChild(newImage);
newImage.style.top = (i * 20) + 'px';
}
#container2 {
width: 340px;
height: 200px;
border: 1px solid black;
position: absolute;
top: 250px;
}
.playingcard {
width: 72px;
height: 100px;
position: absolute;
left: 0px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="styles.css">
<title>Document</title>
</head>
<body>
<div id=container2>
</div>
<script src=script.js></script>
</body>
</html>

Related

image slider with javascript with next previous button

The general appearance of the program is as follows:
enter image description here
the details
In this exercise, we complete a simple slider. You must add the previous and next button in this event. The next or previous image should be displayed when the next or previous button is clicked. You can use the functions defined in the initial project.
When the slider is on the last image and the next button is clicked, the first image should be displayed and also when the first image of the previous button is clicked, the last image should be displayed.
Note: When an image is displayed, its opacity must be 1 and the rest of the images must be 0.
Notes
You are only allowed to make changes to the main.js file.
html code :
const sliderImages = [
"./images/image1.jpg",
"./images/image2.jpg",
"./images/image3.jpg",
"./images/image4.jpg",
];
const sliderDom = document.getElementById("slider");
let currentImage = 0;
function renderImages() {
sliderImages.forEach((image) => {
sliderDom.innerHTML += "<img src='" + image + "' />";
});
}
function clearImages() {
const images = document.getElementsByTagName("img");
for (let i = 0; i < images.length; i++) {
images[i].style.opacity = 0;
}
}
function showImage(image) {
clearImages();
document.getElementsByTagName("img")[image].style.opacity = 1;
}
function init() {
renderImages();
showImage(currentImage);
}
init();
let myBtn = document.querySelector("#prevButton");
myBtn.onclick = function() {
const newImage = (currentImage + 1) % sliderImages.length;
showImage(newImage);
}
let myBtn2 = document.querySelector("#nextButton");
myBtn2.onclick = function() {
const newImage = (currentImage + 1) % sliderImages.length;
showImage(newImage);
}
* {
margin: 0;
padding: 0;
}
button {
padding: 8px;
}
.container {
width: 500px;
margin: 20px auto;
}
#slider {
position: relative;
height: 400px;
margin-bottom: 20px;
}
#slider img {
width: 500px;
height: 400px;
position: absolute;
transition: all .5s;
}
.buttons {
display: flex;
justify-content: space-between;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="style.css">
<title>Slider</title>
</head>
<body>
<div class="container">
<div id="slider"></div>
<div class="buttons">
<button id="prevButton"><</button>
<button id="nextButton">></button>
</div>
</div>
<script src="main.js"></script>
</body>
</html>
var photos = ["images/img1.png", "images/img2.png", "images/img3.png", "images/img4.png"]
var imgTag = document.querySelector("img");
var count = 0;
function next(){
count++;
if(count >= photos.length){
count = 0;
imgTag.src = photos[count];
}else{
imgTag.src = photos[count];
}
}
function prev(){
count--;
if(count < 0){
count = photos.length -1;
imgTag.src = photos[count];
}else{
imgTag.src = photos[count];
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Image Slider</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<button onclick="prev()">prev</button>
<img src="images/img1.png" alt="" style="width:500px; height: 400px;">
<button onclick="next()">Next</button>
<script src="script.js"></script>
</body>
</html>

How to keep a random occurring botton inside the body(Or inside any div)

I Made a button using html, css and js which occurs randomly on the page.But i want the button inside the body tag and it keeps getting out.
HTML CODE:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="main.js" defer></script>
<link rel="stylesheet" href="style.css">
<title>SReflex</title>
</head>
<body>
<button class="random">1 </button>
</body>
</html>
CSS CODE:
*{
margin:0%;
padding:0%;
}
body{
height: 100vh;
width: 100vw;
position: fixed;
}
button.random {
/* looks of the button */
height: 3rem;
width: 3rem;
border: black;
border-style: solid;
border-radius: 50%;
display:block;
position:absolute;
}
JS CODE:
let temp= document.querySelector(".random");
temp.addEventListener("click",change);
function change(){
let posx = Math.floor(Math.random()*1000);
let posy = Math.floor(Math.random()*1000);
let posz = Math.floor(Math.random()*1000);
temp.style.left= posx + "vw";
temp.style.top= posy+ "vh";
temp.style.right= posz+ "vw";
}
How do i make the button to not go off screen, i want the page to not include the scroll bar.
Here is an easy way to do so, it works for the body or for a containing div because it's related to parent size.
check out the snippet.
let temp= document.querySelector(".random");
temp.addEventListener("click",change);
let maxw = temp.parentElement.clientWidth - 50;
let maxh = temp.parentElement.clientHeight - 50;
function change(){
let posx = Math.floor(Math.random() * (maxw));
let posy = Math.floor(Math.random() * (maxh))
temp.style.left= posx + "px";
temp.style.top= posy+ "px";
}
*{
margin:0%;
padding:0%;
}
body{
height: 100vh;
width: 100vw;
position: fixed;
}
button.random {
/* looks of the button */
height: 3rem;
width: 3rem;
border: black;
border-style: solid;
border-radius: 50%;
display:block;
position:absolute;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="main.js" defer></script>
<link rel="stylesheet" href="style.css">
<title>SReflex</title>
</head>
<body>
<button class="random">1 </button>
</body>
</html>
the -50 is to make sure it doesn't cross the edges, you can edit that to suit your needs.

If and Else sentences, on first click

Hi I made this simple animation, when you click on the animate button, the function does not work the first time but it works the second time, how can it be? And what is the solution?
const fadeInOut = () => {
const divElement = document.getElementById('demo');
if (divElement.style.opacity == 0) {
divElement.style.opacity = 1;
} else {
divElement.style.opacity = 0;
}
};
#demo {
width: 300px;
height: 300px;
background: burlywood;
opacity: 1;
display: block;
transition: all 1s;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<script src="function.js" defer></script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="demo"></div>
<button onclick="fadeInOut()">Animate</button>
</body>
</html>
It is because .style checks for an inline style, not the one you set in an external CSS file. You can go around this by setting an initial inline style to your element:
const fadeInOut = () => {
const divElement = document.getElementById('demo');
if (divElement.style.opacity == 0) {
divElement.style.opacity = 1;
} else {
divElement.style.opacity = 0;
}
};
#demo {
width: 300px;
height: 300px;
background: burlywood;
display: block;
transition: all 1s;
}
<div id="demo" style="opacity: 1"></div>
<button onclick="fadeInOut()">Animate</button>

progress bar for loading animation of webpage

I want to make a loading animation for my webpage which will take 8-10 sec to load using JavaScript or Ajax(Which I don't know)
The loading animation is a progress bar
Which I want to stop for every 1 sec for increment of 10% eg( https://codepen.io/gustitammam/pen/RRXGdj )
Bootstrap is not welcomed and I don't want text and percentage on it
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="D:\PORTFOLIO\master.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.js" integrity="sha512-n/4gHW3atM3QqRcbCn6ewmpxcLAHGaDjpEBu4xZd47N0W2oQ+6q7oc3PXstrJYXcbNU1OHdQ1T7pAP+gi5Yu8g==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.6.1/jquery.js" integrity="sha512-qsjFwnCEe/k1YLJDkiRqDgKb+Eq+35xdoeptV7qfI7P6G/kajIF0R6d/9SiOxSkU/aNmHzuipOEYaTUHCJUIeQ==" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/javascript.util/0.12.12/javascript.util.min.js" integrity="sha512-oHBLR38hkpOtf4dW75gdfO7VhEKg2fsitvHZYHZjObc4BPKou2PGenyxA5ZJ8CCqWytBx5wpiSqwVEBy84b7tw==" crossorigin="anonymous"></script>
</head>
<body>
<div id="myprogress">
<div id="mybar">
<span id="incvalue">1%</span>
</div>
</div>
<br> <button onclick="move()">ClickMe</button>
<script>
const move = () => {
var elem = document.getElementById("mybar");
var width = 1;
var id = setInterval(frame, 10)
function frame(){
if(width >= 100){
clearInterval(id);
}else{
width++;
elem.style.width = width + "%";
document.getElementById("incvalue").innerHTML = width + "%";
}
}
}
</script>
</body>
</html>
CSS
html{
scroll-behavior: smooth;
}
body{
background: #181818;
color: #f4eee8;
}
#myprogress{
width: 45%;
background: #181818;
margin: auto;
}
#mybar{
width: 1%;
background: white;
color: white;
text-align: center;
}
In the example you cited, you can just comment out the JS lines where the following fields are set:
.attr and .text
Regarding your desire to omit Bootstrap, however, you are not asking a simple technical question but proposing that somebody write a whole program fragment for you, which is generally not the intended purpose of Stack overflow.
Actually I didn't do it but I don't know his Stack ID so #0_0#1045(From Discord)
HTML
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="D:\PORTFOLIO\master.css">
</head>
<body>
<h3>Dynamic Progress Bar</h3>
<p>Running progress bar from 0% to 100% in 10 seconds</p>
<div class="progress">
<div class="current-progress">
</div>
</div>
</div>
<script src="master.js"></script>
</body>
</html>
CSS
html{
scroll-behavior: smooth;
}
body{
background: #181818;
color: #f4eee8;
height: 100vh;
width: 100vw;
}
.progress {
position: relative;
margin-top: 20px;
height: 20px;
width: 700px;
background-color: #181818;
}
.current-progress {
height: 100%;
width: 0%;
background-color: white;
text-align: center;
transition: all 0.3s;
}
JS
let progressValue = 0;
const progressBar = document.querySelector(".current-progress");
progressBar.style.width = `${progressValue}%`;
const timer = setInterval(() => {
if (progressValue < 100) {
progressValue += 10;
progressBar.style.width = `${progressValue}%`;
}
if (progressValue === 100) {
clearInterval(timer);
}
}, 1000);
Finally Solved!!!

Having problems to generate a random array and visualize it using <div> elements in VS Code?

I am a beginner at web dev and am trying to build a sorting visualizer.
I am unable to get the output for generating a visualization of a random array by using the (div)
element of html.
This is the code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>sorting visualizer</title>
<style>
/* *{
margin: 0;
padding: 0;
} */
#array_container{
position: absolute;
left: 100px;
right: 100px;
bottom: 100px;
height: 100%;
width: 100%;
/* margin-left: 50px;
margin-right: 50px; */
background-color: turquoise;
}
</style>
</head>
<body>
<script>
function random_array(min, max){
return Math.floor(Math.random() * (max - min)) + min;
function generate_array(){
var cont = document.getElementById("array_container");
var bar;
var arr = [];
for ( var i = 0; i < 100; i++){
arr.push(random_array(5, 1000));
bar = document.createElement("div");
bar.style = "height:"+arr[i]+";width:2px;margin:0 1px;background-color:pink;display:inline-block;";
cont.appendChild(bar);
}
}
}
</script>
<div id="array_container">
</div>
<button id="btn1" onclick="generate_array">generate</button>
</body>
</html>
please help me by finding the ERROR and also suggest me some other methods for visualizing array in a bar graph format.
A couple minor syntax bugs I found:
You're missing the parenthesis () at the end of your function name when you pass it to the generate button's onclick
The brackets around your functions were offset, which was causing errors
Your code isn't broken beyond those minor syntax bugs, the problem you're facing is that your generated divs aren't respecting the height you're passing them, because you didn't give them a height unit.
You need to specify a unit like px, otherwise the height will get thrown out and ignored.
Working example (You'll want to adjust some other styles if you want them to fit in your box):
function random_array(min, max) {
return Math.floor(Math.random() * (max - min)) + min;
}
function generate_array() {
var cont = document.getElementById("array_container");
var bar;
var arr = [];
for (var i = 0; i < 100; i++) {
arr.push(random_array(5, 1000));
bar = document.createElement("div");
bar.style = "height:" + arr[i] + "px;width:2px;margin:0 1px;background-color:pink;display:inline-block;";
cont.appendChild(bar);
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>sorting visualizer</title>
<style>
#array_container {
position: absolute;
left: 100px;
right: 100px;
bottom: 100px;
height: 100%;
width: 100%;
background-color: turquoise;
}
</style>
</head>
<body>
<div id="array_container"></div>
<button id="btn1" onclick="generate_array()">generate</button>
</body>
</html>

Categories

Resources