I'm trying to create elements in random locations on the screen but I have run into some trouble. Creating the elements works but when I try to make them have random locations, nothing happens. Thanks for the help in advance.
Here's my code:
var newObject = document.createElement("DIV");
newObject.setAttribute("class", "object");
newObject.setAttribute("id", "powerup");
document.body.appendChild(newObject);
var powerup = document.getElementById("powerup");
var object = document.getElementsByClassName("object");
for (i = 0; i < object.length; i++) {
object[i].style.top = Math.floor(Math.random() * window.innerHeight) + 50 + "px";
object[i].style.left = Math.floor(Math.random() * window.innerWidth) + 50 + "px";
}
function createObject() {
var newObject = document.createElement("DIV");
newObject.setAttribute("class", "object");
newObject.setAttribute("id", "powerup");
document.body.appendChild(newObject);
for (i = 0; i < object.length; i++) {
object[i].style.top = Math.floor(Math.random() * window.innerHeight) + 50 + "px";
object[i].style.left = Math.floor(Math.random() * window.innerWidth) + 50 + "px";
}
}
html, body {
height: 100%;
width: 100%;
margin: 0;
}
#powerup {
background: red;
height: 10px;
width: 10px;
}
<body>
<button onclick="createObject()">Create a Block</button>
</body>
Your code is working correctly. Its able to set top and left of each #powerup element. The only problem is that the position of #powerup is static by default. So you just need to change css of #powerup element to
#powerup {
background: red;
height: 10px;
width: 10px;
position: relative;
}
position: absolute can also be used. Choose the one that fits your requirements.
I made a CodePen with your code.
For those elements to have their top and left properties have an effect, you need to add position: absolute; to the #powerup elements.
#powerup {
background: red;
height: 10px;
width: 10px;
position: absolute;
}
Also, I'm not sure if this is what you intended, but your JavaScript code is selecting a new random location for each pre-existing #powerup element whenever you click the button.
Related
I am having a little bit of trouble with my CSS, as when I change the default zoom (Command + on Mac) of the browser it causes the below image.
When it is at 100% viewport on chrome, it is supposed to look like the below where it fits perfectly in the black box.
My html code is below. For the sake of simplicity, I have only included the container and the tag to show where I wrote it.
<body>
<div class="container">
<div class="container-bars"></div>
</div>
</body>
My CSS code is below:
body {
background-color: rgb(89, 87, 87);
margin-right: auto;
margin-left: auto;
.container {
background-color: rgb(37, 35, 35);
height: 80%;
position: absolute;
width: 60%;
left: 500px;
top: 150px;
}
.bars {
float: left;
border: 1px solid rgb(232, 10, 10);
background-color: rgb(218, 215, 215);
}
The .container is the black box in the background and the body is the grey background. Finally, .bars just represents the CSS for each bar. I am creating a visualizer so the when adding the bars, I am using javascript. The code for adding the bars is below.
const container = document.querySelector('.container');
function add_bars(input) {
const Div = document.createElement('div');
const containerWidth = container.clientWidth;
const containerHeight = container.clientHeight;
const barWidth = containerWidth / inputval - 2;
Div.className = 'bars';
//prettier-ignore
Div.style.height = `${((containerHeight / 100) * input) - 2}px`;
Div.style.width = `${barWidth}px`;
containerBars.append(Div);
}
The input in this case is how large the size of the array is which I am dividing in order to split the width of each bar equally. Any help would be appreciated as to why it exceeds the container when I change how "zoomed" in the browser is. Thanks!
function for_loop(array) {
resetArray();
for (let i = 0; i < array.length; i++) {
add_bars(array[i]);
}
}
When you use % or vh vw in css and change zoom the elements will change their sizes. Try a console.log(document.querySelector(".container")) after and before changing zoom and you will see a different value. In order to avoid that behavior you have to use fixed sizes in your elements. For example:
.container {
background-color: rgb(37, 35, 35);
position: absolute;
height: 600px; // pixels, not % or vh
width: 800px;// the same
left: 150px;
top: 150px;
}
Also, when you make zoom out the problem persist. In order to avoid that just add the next:
* {
box-sizing: border-box;
}
And there is no need to substract 2 px in add_bars function:
...
const barWidth = containerWidth / inputval;
...
Div.style.height = `${((containerHeight / 100) * input)}px`;
...
I am trying to create a vertical slide show on scroll. One picture-screen glide over the next one, and then the second over the third, and so on…
HTML/CSS structure looks as following: external container has display property relative. Inside it there are several containers with images with the property fixed, so that they are all as a card deck and you pull card by card from the top.
JavaScript function should load the first pare of image-pages and follow the amount of scrolled distance changing the index of the image-page and changing the z-index of the layer (the top one: 2, the one blow: 1 and so on...)
var mansDok = []; var paklajAttal = [];
// Find all the slides containers
mansDok = document.getElementsByClassName("slaide");
// Find all the slides IDs
for(i=0; i<mansDok.length; i++) {
paklajAttal[i] = mansDok[i].id;
}
// Height of the browser window
var logAugst = document.documentElement.clientHeight;
// Start function on scrolling the contents
window.onscroll = function() {vertikSlaidrade()};
//
// Slideshow function
function vertikSlaidrade() {
var k = 0; var i = 0, winScroll;
// How far the screen been scrolled
winScroll = document.documentElement.scrollTop || document.body.scrollTop;
// Change slides while scrolling
if(winScroll <= logAugst * 1) {
document.getElementById(paklajAttal[k]).style.zIndex = "2";
document.getElementById(paklajAttal[k]).style.position = "relative";
document.getElementById(paklajAttal[k+1]).style.display = "block";
document.getElementById(paklajAttal[k+1]).style.position = "fixed";
} else if(winScroll <= logAugst * 2) {
document.getElementById(paklajAttal[k+1]).style.zIndex = "3";
document.getElementById(paklajAttal[k+1]).style.position = "relative";
document.getElementById(paklajAttal[k+2]).style.display = "block";
document.getElementById(paklajAttal[k+2]).style.position = "fixed";
} else if(winScroll <= logAugst * 2.8) {
document.getElementById(paklajAttal[k+2]).style.zIndex = "4";
document.getElementById(paklajAttal[k+2]).style.position = "relative";
document.getElementById(paklajAttal[k+3]).style.display = "block";
document.getElementById(paklajAttal[k+3]).style.position = "fixed";
} else if(winScroll > logAugst * 2.8) {
// Run reset function by the end of slides
atiestat();
}
}
// Function to reset the slides properties
function atiestat() {
for(var i=0; i<mansDok.length; i++) {
document.getElementById(paklajAttal[i]).style.zIndex = "0";
document.getElementById(paklajAttal[i]).style.position = "absolute";
document.getElementById(paklajAttal[i]).style.display = "none";
}
// Show the first pair of slides
document.getElementById(paklajAttal[0]).style.display = "block";
document.getElementById(paklajAttal[0]).style.zIndex = "2";
document.getElementById(paklajAttal[1]).style.position = "fixed";
document.getElementById(paklajAttal[1]).style.zIndex = "1";
}
* {box-sizing: border-box;}
html, body{
height: 100%;
margin: 0px;
padding: 0px;
background-color: #000;
font-size: 1em;
}
main {
position: relative;
margin: 0px;
padding: 0px;
width: 100%;
overflow-x: hidden;
overflow-y: auto;
}
/* Page with slide */
.slaide {
position: absolute;
top: 0px;
left: 0px;
z-index: 0;
margin: 0px;
padding: 0px;
width: 100%;
display: none;
}
.slaide img {
width: 1230px; /* Doesn't work below this value !?!? */
}
/* Empty filler */
.tukss {
display: block;
margin: 0px;
padding: 0px;
height: 1000px; /* Do NOT reduce this value!!! */
}
<main>
<div class="slaide" id="lapa1" style="display: block;">
<img src="https://www.w3schools.com/howto/img_parallax.jpg">
</div>
<div class="slaide" id="lapa2">
<img src="https://www.w3schools.com/howto/img_parallax2.jpg">
</div>
<div class="slaide" id="lapa3">
<img src="https://www.w3schools.com/howto/img_parallax3.jpg">
</div>
<div class="tukss" id="tukss"></div>
</main>
May be its not the most elegant version of JS code, but everything works perfectly as I wanted. Somehow it doesn’t work if I change the image size below 1230px or to 100% and reduce the width of the browser window. (Images are from W3Schools.com)
I would appreciate if somebody could help me out with this situation.
this is my getoffset js code to get div width and left
var objRedPacketDivStyle = document.getElementById("styRedPacketAppear");
var objOffset = objRedPacketDivStyle.offset();
var intWidth = objOffset.offsetWidth;
var objWidthStart = objOffset.offset.left;
var objWidthEnd = objWidthStart + intWidth;
alert(objWidthStart + objWidthEnd);
and here is my div and css
<div class="styRedPacketAppear" id="styRedPacketAppear"></div>
#styRedPacketAppear {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 98;
pointer-events: none;
}
This isn't working as .offset() is a jQuery method. Since you don't have jquery you need to use vanilla javascript to achieve this.
You can use:
element.offsetWidth: "returns the layout width of an element as an integer." - MDN
element.offsetLeft: "returns the number of pixels that the upper left corner of the current element is offset to the left within the HTMLElement.offsetParent node." - MDN
Using these two properties will resolve your issue:
var objRedPacketDivStyle = document.getElementById("styRedPacketAppear");
// Remove this: var objOffset = objRedPacketDivStyle.position.offset();
var intWidth = objRedPacketDivStyle.offsetWidth;
var objWidthStart = objRedPacketDivStyle.offsetLeft;
var objWidthEnd = objWidthStart + intWidth;
alert(objWidthStart + objWidthEnd);
#styRedPacketAppear {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 98;
pointer-events: none;
}
<div class="styRedPacketAppear" id="styRedPacketAppear"></div>
The offsetTop property returns the top position (in pixels) relative to the top of the offsetParent element.
The returned value includes:
-the top position, and margin of the element
-the top padding, scrollbar and border of the offsetParent element.
#test {
top: 100px;
margin: 10px;
padding: 10px;
width: 300px;
position: fixed;
border: 5px solid black
}
var testDiv = document.getElementById("test");
document.getElementById("demo").innerHTML = testDiv.offsetTop;
Result-offsetTop is: 110
There is a circle and some object around it.the objects number may vary from 1 to n (dynamic).
How can i place all this objects around the circle automatically ??
Tnx in advance.
Here is a way of doing it. I've added comments in the code to explain the steps. I've taken the liberty to use just colored divs instead of images, but the effect is the same.
// Editor to change the number of persons dynamically
var nr = document.getElementById('nr');
nr.addEventListener('keyup', function(){updatePersons();});
// The globe
var globe = document.getElementById('globe');
// A function to reinitialize the persons
function updatePersons() {
var personCount = parseInt(nr.value);
globe.innerHTML = ''; // A bit dirty way to remove all previous peeps
// Just add them in a loop, and apply a transformation.
for (var i = 0; i < personCount; i++) {
var person = document.createElement('div');
person.className = 'mens';
var rotation = i * (360 / personCount);
console.log(rotation);
person.style.transform = 'translate(125px, -100px) rotate(' + rotation + 'deg)';
globe.appendChild(person);
}
}
// Initial positioning of persons.
updatePersons();
#nr {
position: relative;
z-index: 1;
}
.corea {
background-color: blue;
border-radius: 50%;
width: 300px;
height: 300px;
position: relative;
}
.mens {
position: absolute; /* Needed, otherwise they influence each other */
width: 50px;
height: 100px;
background-color: red;
transform-origin: 25px 250px;
/* Transform is set in Javascript */
x-transform: translate(125px, -100px) rotate(180deg);
}
<input id="nr" value="5">
<div id="globe" class="corea">
</div>
I'm trying to write a facebook like chatbox, but i've encountered a small problem.
I'm using the following code (it's only test code, so it's not really clean):
css code:
#messenger {
position: fixed;
bottom: 0px;
right: 10px;
width: 200px;
height: 300px;
z-index: 4;
background-color: #ECECEC;
border: 1px solid #000;
}
#messenger.p {
text-align: right;
}
#contacts {
margin: 5px 5px 5px 5px;
}
#chatspace {
position: fixed;
bottom: 0px;
right: 240px;
height: 20px;
left: 20px;
background-color: #ECECEC;
border: 1px solid #000;
z-index: 4;
}
.chatbox {
position: absolute;
bottom: 0px;
width: 200px;
height: 200px;
z-index: 4;
background-color: #ECECEC;
border: 1px solid #000;
}
html/javascript code:
<script type="text/javascript">
var i = 0;
function oc_chatbox() {
if (i == 0) {
document.getElementById('contacts').style.visibility = 'hidden';
document.getElementById('messenger').style.height = '20px';
i = 1;
}
else {
document.getElementById('contacts').style.visibility = 'visible';
document.getElementById('messenger').style.height = '300px';
i = 0;
}
}
function new_chat(userid) {
var new_right;
new_right = document.getElementById('messenger').style.right;
//alert('old value: '+ new_right);
new_right += 20;
//alert('New value of right: '+ new_right);
document.getElementById('chatspace').innerHTML = '<div id="'+userid+'" class="chatbox" style="right: '+new_right+'px;"></div>';
//document.write('<div id="'+userid+'" class="chatbox" style="right: '+new_right+'px;"></div>');
}
</script>
<div id="chatspace"></div>
<div id="messenger">
<p>Collapse</p>
<div id="contacts">
<ul>
<li>contact A</li>
</ul>
</div>
</div>
the problem is, that when I try to add new chats to the chatbar, i can't seem the place them next to each other.
anyone who can help ?
EDIT:
so i changed to javascript code to:
var last = null;
function new_chat(userid) {
if(userid==null)
userid = "user666";
var new_right;
var margin = 10;
var messenger = window.last==null?document.getElementById('messenger'):window.last; //Take the messenger or the last added chat
new_right = document.body.clientWidth-messenger.offsetLeft; //Compute the window size
console.log(new_right); //Log the number
new_right += margin; //keep spaces between divs
var newChat = document.createElement("div"); //DOM create DIV
newChat.id = userid;
newChat.className = "chatbox shadow";
newChat.style.right = new_right+"px";
newChat.innerHTML = '<p>'+userid+'</p><p><textarea></textarea></p>';
window.last = newChat; //Remember whichever is last
document.body.appendChild(newChat);
}
and now it works, thanks !
You cannot get an element right offset using its style, unlest the style is set and valid. Instead you must get element.offsetLeft and size of window area and do this:
new_right = windowSize()[0]-messenger.offsetLeft;
Where window size is this function.
Here is my, working, version of your function:
var last = null;
function new_chat(userid) {
if(userid==null)
userid = "user666";
var new_right;
var margin = 20;
var messenger = window.last==null?document.getElementById('messenger'):window.last; //Take the messenger or the last added chat
new_right = windowSize()[0]-messenger.offsetLeft; //Compute the window size
console.log(new_right); //Log the number
new_right += margin; //keep spaces between divs
var newChat = document.createElement("div"); //DOM create DIV
newChat.id = userid;
newChat.className = "chatbox";
newChat.style.right = new_right+"px";
window.last = newChat; //Remember whichever is last
document.body.appendChild(newChat);
}
You may get errors if console is not defined in your brouwser. But in such case you should take a better browser. Normally, the if(console!=null) is put in code.
And here is the link.
You should try adding a float style.
.chatbox {
float: right;
}
Add that to your chatbox styles. You may need to mess around a bit to make sure the float doesn't mess with your other elements. You may need a better container for them.
If you want to get really fun, you can add .draggable() from jQuery, and you can have them snap to your chat bar. You can then change the order of your chats.