Place Div in Div with a specific margin (10px) - javascript

I tried do make a Webpage like this(Fullscreen):
And the color of each of them should change randomly every second.
This is the JS that I have:
<script>
var tid = setInterval(chngColor, 1000);
function chngColor()
{
document.body.style.backgroundColor = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
}
</script>
Now I tried to make a fullscreen div(as big as the body) and place other divs inside the first div with the margin:10px on each side. I cant figure out the style of the divs.
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
background-color="myFunction();";
z-index: 10;
margin-bottom:10px;
margin-top:10px;
margin-left:10px;
margin-right:10px;
This doesn't work?

You can't use a JavaScript function inside CSS code. What you should do instead is to use your chngColor function on every element that you want to change it's background.
Changing you function to take an dom element as a parameter
function chngColor(el)
{
el.style.backgroundColor = '#' + (Math.random()*0xFFFFFF<<0).toString(16);
}
And supposing your elements have a common specific class, let's say "foo", you can iterate all of them and use the function for every one of them:
var foos = document.getElementsByClassName('foo');
for(var i=0; i <foos.length;i++){
chngColor(foos[i]);
}
Put that in a function so you can use in setInterval and you are good to go.

Related

Is there a way to create a button and a click event on this js function?

I've been trying for more than a day to make three implementations in this code, but still without success.
1° I need to create a button inside this page.
I've already tried to create a very normal button through html and css, but the fireworks page covers and hides the button element.
All elements displayed on the page are purely created within the JS file.
Here are the html and css
HTML
<canvas id="fireworksidButton" href="#" class="myButton">Click here</canvas>
<canvas id="firework"></canvas>
<canvas id="city"></canvas>
CSS
html {
height: 100%;
}
body {
margin: 0;
height: 100%;
}
canvas {
position: absolute;
top: 0;
left: 0;
}
#app {
position: absolute;
top: 0;
left: 0;
}
.myButton {
background-color:#44c767;
border-radius:28px;
border:1px solid #18ab29;
display:inline-block;
cursor:pointer;
color:#ffffff;
font-family:Arial;
font-size:28px;
padding:16px 31px;
text-decoration:none;
text-shadow:0px 1px 0px #2f6627;
}
.myButton:hover {
background-color:#5cbf2a;
}
.myButton:active {
position:relative;
top:1px;
}
2° I need to remove the Loop generated by the function.
I've already tried disabling this render action, but unfortunately it didn't work.
Here is the part of the script that renders the loop action.
let _pre = OrbitCalculator.pre_render();
(function loop(count) {
if (render_end) {
render_end = false;
_pre = OrbitCalculator.pre_render();
loop(0);
return;
}
if (count === MAX_AMOUNT_OF_FIREWORKS) {
count--;
} else {
fireworks.push(_pre[count]);
}
setTimeout(() => loop(++count), INTERVAL);
})(0);
3° I need to create a click event so that when the button is clicked, the function will be executed.
I´d like wrappe the function that triggers the Loop with the code below if it make sense.
function fireworksTrigger(){
document.querySelector('#fireworksidButton').addEventListener("click", async () => {
});
To make the function run, there is a dependence of the following library:
We can find the library inserted in the compiler´s settings.
[Library]https://cdnjs.cloudflare.com/ajax/libs/pixi.js/5.3.3/pixi.min.js
Here is the whole code running on the compiler. 599 Lines of code. That´s why i didn`t post the whole script here.
[Fireworks]https://codepen.io/paulodoporto/pen/Jjverod
What should I do please? Any Light?
Thank you so much in advance!
First i dont think that putting the button inside the canvas element is the best way to do it, you might just want to do <button class='myButton'>Click here<button>. To make the button not be covered by the canvas, i would suggest that you change the z-index like freedomn-m said. A higher z-index means that its placed higher when rendering, so make sure that the button has a higher z-index than the canvas. Alternatively, you can just put the button html after the canvas and that should automatically make the button on thop, since its rendered after.
I'm not 100% sure what your trying do do here but it looks like your using recursion so i would just use async and then sleep like this
const sleep = ms => new Promise(res => setTimeout(res, ms));
(async () => {
/*whatever u wanna do*/
await sleep(2);
})();
You should just be able to put whatever function u wanna call inside the addeventlistener('click',//whatever') but this might not work unless you call the function fireworksTrigger in a main/setup run before the main loop starts
Hope this helps

Refresh a page with new div grid

I'm trying to make a grid of divs that, when mouseentered change color. Then, when the a button is clicked and new number is entered to then generate a new grid with a side length of that many divs. I'm new to javascript and jQuery and can't figure out why my code won't generate the divs.
here's my script
$('.block').mouseenter(function () {
$(this).css('background-color', 'black');
});
function newGrid(x) {
for (i = 0; i > x * x; i++) {
$('.container').append('<div class="block"></div>');
}
$('.block').height(960 / );
$('.block').width(960 / );
}
function clearContainer() {
$('.block').remove();
}
function askGrid() {
var num = prompt("enter box length");
clearContainer();
newGrid(num);
}
function firstGrid() {
newGrid(16);
$('#reset').click(function () {
askGrid();
});
}
$(document).ready(firstGrid);
here's my css
.container {
margin: 30px auto 0px auto;
height: 960px;
width: 960px;
border: 1px solid black;
}
.block {
border:0px;
margin:0px;
padding:0px;
float:left;
background-color: yellow;
}
#reset {
display:block;
padding:5px 20px;
margin:0 auto;
}
html has a css reset and in the body i have a button with id="reset" and a div with class="container"
thanks!
Several problems:
The slash when setting height and width is wrong (either is 960 divided by something or just 960)
The for loop is wrong: it should be
for (i = 0; i < x * x; i++)
And the css thing is not going to apply since there are no .block elements when executed. You should probably move it into newGrid
You have a bug here for (i = 0; i > x * x; i++) it should be i < x.
And im not sure what this is
$('.block').height(960 / );
$('.block').width(960 / );
you can set the height and width respectively in the css
Also you need to this for the mouseenter event to work
$('.container').on('mouseenter','.block',function () {
$(this).css('background-color', 'black');
});
Since the items added are dynamic.
Welcome to jquery, a world of excitement and pain!
This code
$('.block').mouseenter(function () {
$(this).css('background-color', 'black');
});
binds the hover function to all existing .block elements on the page when it is run. It's at the top of your script so it'll execute once, binding this property to all .block elements when the page loads, but not to .block elements created after. To fix this add it inside your "newGrid" function so it rebinds each new element as they are created.
In your loop, you want for (i = 1; i < x * x; i++), starting index from 1 rather than 0, or else you'll have an off by 1 error and create an extra box.
To set the proper heights of .block, you want to divide your .container's dimentions by x, the size of block:
$('.block').height(960 / x);
$('.block').width(960 / x);
The following are general programming tips:
As a good practice, functions should have a specific job and only do that job. I moved the clearContainer call to inside newGrid, because it should be the function that builds the new grid that clears the old one, not the one called askGrid. askGrid should do as it is named, and only ask for your new grid dimension.
You should do a validation on the number received through askGrid. If the user types something that isn't a number, or a negative number, or 0, you shouldn't start making boxes or newGrid will break. I added a loop to keep asking for a size until a proper dimension is provided, but you can chose your behaviour.
I changed the variable "x" to "block_length" since variables should be given names indicative of that they mean, so that there aren't a bunch of mysterious variables all over the place called x, y, z that you can't tell what they mean from a glance.
Demo in this fiddle!

How to load an initial set of images, then animate between them randomly without jQuery

On my page I have a gallery (just a div) with several images on it. I want to show the first 9 images immediately, then load more images and use CSS transitions to animate between the existing images.
Loading the initial images is easy but I do not know the best way to load the next set of images and then start animating (using the CSS Transform property). So far this is what I have:
HTML (abbreviated):
<div id="mainContainer">
<div class="imageHolder"><img class="homeImages" src="test.png"></div>
<div class="imageHolder"><img class="homeImages" src="test1.png"></div>
<div class="imageHolder"><img class="homeImages" src="test3.png"></div>
</div>
CSS (abbreviated):
img {
display: inline;
position: relative;
margin: 0;
padding: 0;
width: 30%;
}
.changed.opaque {
opacity: 0;
border: 2px solid red;
}
I am looking to do a variety of effects, the most simple one would be to change the opacity and fade one image over the other. To load the next set of images I have this:
Javascript:
var imageArray = [
'test2.png',
'test3.png',
'test4.png',
'test5.png',
'test6.png',
];
var imageNodeArray = [];
for(var i = imageArray.length - 1; i >= 0; i -= 1) {
var img = new Image();
img.onload = function() {
imageNodeArray.push(this);
};
img.src = imageArray[i];
}
document.onclick = function() {
imageNodeArray[0].setAttribute('class', 'changed.opaque');
divs[0].appendChild(imageNodeArray[0])
}
This does add an image to my mainContainer however, even though I can tell from devTools that it has the changed.opaque class applied to it, no opacity is shown on the added image.
I am curious about this. I would also like to know the best way to "stack" images to have a bunch to animate through. I am not sure that appending child is right.... Thank you
function animate() {
var index = Math.floor((Math.random() * document.querySelectorAll('#mainContainer > .imageHolder').length + 1));
var current = document.querySelector('.top');
var next = document.querySelector('.imageHolder:nth-of-type(' + index + ')');
current.className = "imageHolder";
next.className += "top";
}
Should be able to handle and switch between any dynamically inserted images.
Currently using:
.imageHolder {
display: none;
}
.top {
display: inherit;
}
to switch the image is just a simple implementation.
Here's the working fiddle: http://jsfiddle.net/e9dxN/1/
Alternative implementation: http://jsfiddle.net/e9dxN/6/

Change DIV margin on interval

I am trying to change the margin of each element, using setAttribute.
How can I able to use my variable dist "distance" to decrease value until 10, every after delay "interval"?
var dist=200; var speed = 2000;
function slideLeft(x){
dist--;
slideSet[x].setAttribute("style","margin-right:"+dist+"px;");
setTimeout(slideLeft(x), delay);
}
Take these style and elements for example...
.widiv { margin-right:200px; }
<div>
<div class="widiv" ></div>
<div class="widiv" ></div>
</div>
Thanks a lot.
Here's your code with some changes: See fiddle http://jsfiddle.net/chrismoutray/4p3xX/
var dist = 200, delay = 500,
slideSet = document.getElementsByTagName('div');
function slideLeft(x) {
dist--;
if (dist < 0) return;
slideSet[x].setAttribute("style", "margin-right:" + dist + "px;");
setTimeout(function() {
slideLeft(x);
}, delay);
}
slideLeft(1);
With a few additions to the styling:
.widiv {
margin-right:200px;
float:left;
width: 100px;
border: 1px solid black;
height: 100px; }
The main differences are that when calling setTimeout I'm using a function delegate (function() { <your code here> }) to call the slideLeft method so that x variable is used correctly - I don't think you can pass a statement into setTimeout without doing it this way.
Also in styling the divs I made sure to include a float left other wise the change to margin right doesn't make sense - should this be margin left instead?

Wait cursor over entire html page

Is it possible to set the cursor to 'wait' on the entire html page in a simple way? The idea is to show the user that something is going on while an ajax call is being completed. The code below shows a simplified version of what I tried and also demonstrate the problems I run into:
if an element (#id1) has a cursor style set it will ignore the one set on body (obviously)
some elements have a default cursor style (a) and will not show the wait cursor on hover
the body element has a certain height depending on the content and if the page is short, the cursor will not show below the footer
The test:
<html>
<head>
<style type="text/css">
#id1 {
background-color: #06f;
cursor: pointer;
}
#id2 {
background-color: #f60;
}
</style>
</head>
<body>
<div id="id1">cursor: pointer</div>
<div id="id2">no cursor</div>
Do something
</body>
</html>
Later edit...
It worked in firefox and IE with:
div#mask { display: none; cursor: wait; z-index: 9999;
position: absolute; top: 0; left: 0; height: 100%;
width: 100%; background-color: #fff; opacity: 0; filter: alpha(opacity = 0);}
<a href="#" onclick="document.getElementById('mask').style.display = 'block'; return false">
Do something</a>
The problem with (or feature of) this solution is that it will prevent clicks because of the overlapping div (thanks Kibbee)
Later later edit...
A simpler solution from Dorward:
.wait, .wait * { cursor: wait !important; }
and then
Do something
This solution only shows the wait cursor but allows clicks.
If you use this slightly modified version of the CSS you posted from Dorward,
html.wait, html.wait * { cursor: wait !important; }
you can then add some really simple jQuery to work for all ajax calls:
$(document).ready(function () {
$(document).ajaxStart(function () { $("html").addClass("wait"); });
$(document).ajaxStop(function () { $("html").removeClass("wait"); });
});
or, for older jQuery versions (before 1.9):
$(document).ready(function () {
$("html").ajaxStart(function () { $(this).addClass("wait"); });
$("html").ajaxStop(function () { $(this).removeClass("wait"); });
});
I understand you may not have control over this, but you might instead go for a "masking" div that covers the entire body with a z-index higher than 1. The center part of the div could contain a loading message if you like.
Then, you can set the cursor to wait on the div and don't have to worry about links as they are "under" your masking div. Here's some example CSS for the "masking div":
body { height: 100%; }
div#mask { cursor: wait; z-index: 999; height: 100%; width: 100%; }
This seems to work in firefox
<style>
*{ cursor: inherit;}
body{ cursor: wait;}
</style>
The * part ensures that the cursor doesn't change when you hover over a link. Although links will still be clickable.
I have been struggling with this problem for hours today.
Basically everything was working just fine in FireFox but (of course) not in IE.
In IE the wait cursor was showing AFTER the time consuming function was executed.
I finally found the trick on this site:
http://www.codingforums.com/archive/index.php/t-37185.html
Code:
//...
document.body.style.cursor = 'wait';
setTimeout(this.SomeLongFunction, 1);
//setTimeout syntax when calling a function with parameters
//setTimeout(function() {MyClass.SomeLongFunction(someParam);}, 1);
//no () after function name this is a function ref not a function call
setTimeout(this.SetDefaultCursor, 1);
...
function SetDefaultCursor() {document.body.style.cursor = 'default';}
function SomeLongFunction(someParam) {...}
My code runs in a JavaScript class hence the this and MyClass (MyClass is a singleton).
I had the same problems when trying to display a div as described on this page. In IE it was showing after the function had been executed. So I guess this trick would solve that problem too.
Thanks a zillion time to glenngv the author of the post. You really made my day!!!
Easiest way I know is using JQuery like this:
$('*').css('cursor','wait');
css: .waiting * { cursor: 'wait' }
jQuery: $('body').toggleClass('waiting');
Why don't you just use one of those fancy loading graphics (eg: http://ajaxload.info/)? The waiting cursor is for the browser itself - so whenever it appears it has something to do with the browser and not with the page.
To set the cursor from JavaScript for the whole window, use:
document.documentElement.style.cursor = 'wait';
From CSS:
html { cursor: wait; }
Add further logic as needed.
Try the css:
html.waiting {
cursor: wait;
}
It seems that if the property body is used as apposed to html it doesn't show the wait cursor over the whole page. Furthermore if you use a css class you can easily control when it actually shows it.
Here is a more elaborate solution that does not require external CSS:
function changeCursor(elem, cursor, decendents) {
if (!elem) elem=$('body');
// remove all classes starting with changeCursor-
elem.removeClass (function (index, css) {
return (css.match (/(^|\s)changeCursor-\S+/g) || []).join(' ');
});
if (!cursor) return;
if (typeof decendents==='undefined' || decendents===null) decendents=true;
let cname;
if (decendents) {
cname='changeCursor-Dec-'+cursor;
if ($('style:contains("'+cname+'")').length < 1) $('<style>').text('.'+cname+' , .'+cname+' * { cursor: '+cursor+' !important; }').appendTo('head');
} else {
cname='changeCursor-'+cursor;
if ($('style:contains("'+cname+'")').length < 1) $('<style>').text('.'+cname+' { cursor: '+cursor+' !important; }').appendTo('head');
}
elem.addClass(cname);
}
with this you can do:
changeCursor(, 'wait'); // wait cursor on all decendents of body
changeCursor($('#id'), 'wait', false); // wait cursor on elem with id only
changeCursor(); // remove changed cursor from body
I used a adaptation of Eric Wendelin's solution. It will show a transparent, animated overlay wait-div over the whole body, the click will be blocked by the wait-div while visible:
css:
div#waitMask {
z-index: 999;
position: absolute;
top: 0;
right: 0;
height: 100%;
width: 100%;
cursor: wait;
background-color: #000;
opacity: 0;
transition-duration: 0.5s;
-webkit-transition-duration: 0.5s;
}
js:
// to show it
$("#waitMask").show();
$("#waitMask").css("opacity"); // must read it first
$("#waitMask").css("opacity", "0.8");
...
// to hide it
$("#waitMask").css("opacity", "0");
setTimeout(function() {
$("#waitMask").hide();
}, 500) // wait for animation to end
html:
<body>
<div id="waitMask" style="display:none;"> </div>
... rest of html ...
My Two pence:
Step 1:
Declare an array. This will be used to store the original cursors that were assigned:
var vArrOriginalCursors = new Array(2);
Step 2:
Implement the function cursorModifyEntirePage
function CursorModifyEntirePage(CursorType){
var elements = document.body.getElementsByTagName('*');
alert("These are the elements found:" + elements.length);
let lclCntr = 0;
vArrOriginalCursors.length = elements.length;
for(lclCntr = 0; lclCntr < elements.length; lclCntr++){
vArrOriginalCursors[lclCntr] = elements[lclCntr].style.cursor;
elements[lclCntr].style.cursor = CursorType;
}
}
What it does:
Gets all the elements on the page. Stores the original cursors assigned to them in the array declared in step 1. Modifies the cursors to the desired cursor as passed by parameter CursorType
Step 3:
Restore the cursors on the page
function CursorRestoreEntirePage(){
let lclCntr = 0;
var elements = document.body.getElementsByTagName('*');
for(lclCntr = 0; lclCntr < elements.length; lclCntr++){
elements[lclCntr].style.cursor = vArrOriginalCursors[lclCntr];
}
}
I have run this in an application and it works fine.
Only caveat is that I have not tested it when you are dynamically adding the elements.
BlockUI is the answer for everything. Give it a try.
http://www.malsup.com/jquery/block/
This pure JavaScript seems to work pretty well ... tested on FireFox, Chrome, and Edge browsers.
I'm not sure about the performance of this if you had an overabundance of elements on your page and a slow computer ... try it and see.
Set cursor for all elements to wait:
Object.values(document.querySelectorAll('*')).forEach(element => element.style.cursor = "wait");
Set cursor for all elements back to default:
Object.values(document.querySelectorAll('*')).forEach(element => element.style.cursor = "default");
An alternative (and perhaps a bit more readable) version would be to create a setCursor function as follows:
function setCursor(cursor)
{
var x = document.querySelectorAll("*");
for (var i = 0; i < x.length; i++)
{
x[i].style.cursor = cursor;
}
}
and then call
setCursor("wait");
and
setCursor("default");
to set the wait cursor and default cursor respectively.
Lots of good answers already, but none of them mentions the <dialog> element.
Using this element we can create a solution similar to the masking <div>.
Here we use showModal() to "hide" elements, and we use ::backdrop to set the cursor style to wait on the entire page:
function showWaitDialog() {
document.getElementById('id_dialog').showModal();
}
#id_dialog, #id_dialog::backdrop {
cursor: wait;
}
<button onclick="showWaitDialog()">click me</button>
<dialog id="id_dialog">busy...</dialog>
The dialog is hidden by default, and can be shown using either the show() method, or the showModal() method, which prevents clicking outside the dialog.
The dialog can be forced to close using the close() method, if necessary.
However, if your button links to another page, for example, then the dialog will disappear automatically as soon as the new page is loaded.
Note that the dialog can also be closed at any time by hitting the Esc key.
CSS can be used to style the dialog however you like.
The example uses the html onclick attribute, just for simplicity. Obviously, addEventListener() could also be used.
Late to the party but simply give the Html tag an id by targeting
document.documentElement
and in the CSS place at the top
html#wait * {
cursor: wait !important;
}
and simply remove it when you want to stop this cursor.

Categories

Resources