Create Element with id and styles using pure JS - javascript

I build a small function appending an element with an id and styles.
And know my question why does this code not work?
window.addEventListener("load",function(e){
var inButton = document.createElement("DIV"),
body = document.body;
inButton.id = "button";
inButton.style = function (){
height = "200px";
width = "400px";
position = "fixed";
top = "50%";
left = "50%";
marginLeft = -1*(this.width / 2);
marginTop = -1*(this.height / 2);
};
body.appendChild(inButton);
}, false);
I use the following html:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<meta name="description"/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta http-equiv="x-ua-compatible" content="ie=edge" />
<script type="text/javascript" src="js/vendor/modernizr-.8.3.min.js"></script>
</head>
<body>
<script type="text/javascript" src="js/plugins.js"></script>
<script type="text/javascript" src="js/main.js"></script>
</body>
</html>
The Js Code is inside the main.js.
I checked the path again and again, but the path is totally correct.

You are not setting style property correctly. Rest of code is correct.
Here's an example
window.addEventListener("load", function(e) {
var inButton = document.createElement("DIV"),
body = document.body;
inButton.id = "button";
inButton.innerHTML = "Yahooooooooooooooo"; //For example
inButton.style.height = "200px";
inButton.style.width = "400px";
inButton.style.position = "fixed";
inButton.style.top = "50%";
inButton.style.left = "50%";
inButton.style.marginLeft = -1 * (this.width / 2);
inButton.style.marginTop = -1 * (this.height / 2);
body.appendChild(inButton);
}, false);

Related

I want to convert paper.js Examples from paperscript to javascript

I am Japanese and I apologize for my unnatural English, but I would appreciate it if you could read it.
I learned how to convert paperscript to javascript from the official documentation.
Its means are as follows
Change the type attribute of the script tag to text/paperscript. <script type="text/paperscript" src="./main.js"></script>
Enable Paperscope for global use.  paper.install(window)
Specify the target of the canvas. paper.setup(document.getElementById("myCanvas"))
Write the main code in the onload window.onload = function(){ /* add main code */ }
Finally, add paper.view.draw()
The onFrame and onResize transforms as follows. view.onFrame = function(event) {}
onMouseDown, onMouseUp, onMouseDrag, onMouseMove, etc. are converted as follows. var customTool = new Tool(); customTool.onMouseDown = function(event) {};
I have tried these methods, but applying these to the Examples on the paper.js official site does not work correctly.
The following code is the result of trying these.
<!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 type="text/javascript" src="https://unpkg.com/paper"></script>
<script type="text/javascript" src="./main.js"></script>
<title>Document</title>
</head>
<body>
<canvas id="myCanvas"></canvas>
</body>
</html>
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function(){
paper.setup(myCanvas)
var points = 25;
// The distance between the points:
var length = 35;
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++)
path.add(start + new Point(i * length, 0));
customTool.onMouseMove=function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
var vector = segment.point - nextSegment.point;
vector.length = length;
nextSegment.point = segment.point - vector;
}
path.smooth({ type: 'continuous' });
}
customTool.onMouseDown=function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp=function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
The original paperscript can be found here.
What is the problem with this code?
Thank you for reading to the end!
The var vector in the for loop is not getting the correct values in your code. Change the math operators and it will work like the paperjs demo.
Math operators (+ - * /) for vector only works in paperscript. In Javascript, use .add() .subtract() .multiply() .divide(). see http://paperjs.org/reference/point/#subtract-point
// paperscript
segment.point - nextSegment.point
// javascript
segment.point.subtract(nextSegment.point)
Here's a working demo of your example
paper.install(window);
console.log("run test")
var myCanvas = document.getElementById("myCanvas")
var customTool = new Tool();
window.onload = function() {
paper.setup(myCanvas)
var points = 15; //25
// The distance between the points:
var length = 20; //35
var path = new Path({
strokeColor: '#E4141B',
strokeWidth: 20,
strokeCap: 'round'
});
var start = view.center / [10, 1];
for (var i = 0; i < points; i++) {
path.add(start + new Point(i * length, 0));
}
customTool.onMouseMove = function(event) {
path.firstSegment.point = event.point;
for (var i = 0; i < points - 1; i++) {
var segment = path.segments[i];
var nextSegment = segment.next;
//var vector = segment.point - nextSegment.point;
var vector = segment.point.subtract(nextSegment.point);
vector.length = length;
//nextSegment.point = segment.point - vector;
nextSegment.point = segment.point.subtract(vector);
}
path.smooth({
type: 'continuous'
});
}
customTool.onMouseDown = function(event) {
path.fullySelected = true;
path.strokeColor = '#e08285';
}
customTool.onMouseUp = function(event) {
path.fullySelected = false;
path.strokeColor = '#e4141b';
}
view.draw();
}
html,
body {
margin: 0
}
canvas {
border: 1px solid red;
}
<!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 type="text/javascript" src="https://unpkg.com/paper"></script>
<!-- you can add this back in -->
<!-- <script type="text/javascript" src="./main.js"></script> -->
<title>Document</title>
</head>
<body>
<!-- set any size you want, or use CSS/JS to make this resizable -->
<canvas id="myCanvas" width="600" height="150"></canvas>
</body>
</html>

Github Pages as Static Image Hosting

I am trying to use GitHub pages to host static images for a website I am working on. The website randomizes div locations across the page, and it's supposed to use the photos from the repository. Here is the repository that is hosting the images.
The issue is that the images are not loading from the Github pages. Am I not referencing the photos correctly in the Javascript? Here is a photo that shows what the page looks like when I run it. As you can see, none of the images load into the webpage. Not sure if I am referencing the photo incorrectly in the JS, or if I need to add any HTML code to reference the photos. Either way, I would really appreciate any help. :)
HTML:
<!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>page</title>
<link rel="stylesheet" href="assets/css/style.css">
<script src="assets/js/script.js"></script>
<!-- <script src="https://code.jquery.com/jquery-3.6.1.js" integrity="sha256-3zlB5s2uwoUzrXK3BT7AX3FyvojsraNFxCc2vC/7pNI=" crossorigin="anonymous"></script> -->
</head>
<body>
<h1><b>Issy B. Designs</b></h1><br>
<div class="random"></div>
</body>
</html>
JS:
const imgPoss = [];
let maxX, maxY;
function placeImg() {
const NUM_OF_IMAGES = 90; // set this to however images you have in the directory.
const randImg = Math.random() * NUM_OF_IMAGES;
const imgSrc = 'https://elimcgehee.github.io/staticimages/gallery/' + randImg.toString() + '.png';
const {random: r} = Math;
const x = r() * maxX;
const y = r() * maxY;
if(!isOverlap(x,y)) {
var link = `<img class="random" style="left: ${x}px; top: ${y}px;" src="${imgSrc}" />`;
var bodyHtml = document.body.innerHTML;
document.body.innerHTML = bodyHtml + link;
imgPoss.push({x, y}); // record all img positions
}
}
function isOverlap(x, y) { // return true if overlapping
const img = {x: 128, y:160};
for(const imgPos of imgPoss) {
if( x>imgPos.x-img.x && x<imgPos.x+img.x &&
y>imgPos.y-img.y && y<imgPos.y+img.y ) return true;
}
return false;
}
onload = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
setInterval(placeImg, 10);
}
onresize = function() {
maxX = innerWidth - 128;
maxY = innerHeight - 160;
}
In JavaScript Math.random() returns float between 0 and 1. By multiplying it by 90 you get a float, but all your photos are intigers. And since your pictures start from 10.png it should look like this
const NUM_OF_IMAGES = 90; // set this to however images you have in the directory.
const START_OF_IMAGES = 10;
const randImg = Math.round(Math.random() * NUM_OF_IMAGES + START_OF_IMAGES);
const imgSrc = 'https://elimcgehee.github.io/staticimages/gallery/' + randImg.toString() + '.png';

How to make a button move?

I'm going to make 8 buttons move down to the bottom of screen one by one but I have a problem
here is my code :
var i = 0;
var j = 0;
while(i < 7){
i++;
interval[i] = setInterval(interval(), 10);
function interval(){
y[j]++;
if (parseInt(y[j]) >= window.innerHeight) {
if(j == y.length - 1){
debugger;
return clearInterval(interval[j]);
}
j++;
return interval();
}
button[j].style.top = y[j] + "px";
}
console.log(i);
}
var body = document.getElementById("body");
var button = [];
body.style.position = "relative";
var y = [];
for (var i = 0; i < 8; i++) {
y[i] = 0;
button[i] = document.createElement("button");
button[i].onclick = clickme();
button[i].innerHTML = "بازی";
button[i].style.fontFamily = "b nazanin";
button[i].style.fontSize = "32pt";
button[i].style.position = "absolute";
body.appendChild(button[i]);
}
var i = 0;
var j = 0;
var Interval = setInterval(interval(), 10);
function interval(){
y[j]++;
if (parseInt(y[j]) >= window.innerHeight) {
if(j == y.length - 1){
debugger;
return clearInterval(Interval[j]);
}
j++;
return interval();
}
button[j].style.top = y[j] + "px";
}
/*
var button2 = document.createElement("button");
button2.onclick = clickme();
button2.innerHTML = "بازی";
button2.style.fontFamily = "b nazanin";
button2.style.fontSize = "32pt";
body.appendChild(button);
body.appendChild(button2);
body.style.position = "relative";
button2.style.position = "absolute";
button.style.position = "absolute";
*/
function clickme() {
}
<!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>
<link rel="stylesheet" href="index.css">
</head>
<body id="body">
</body>
<script src="index.js"></script>
</html>
Code explained :
button is my buttons element array.
y is my button's Tops array.
My problem is that the first button will move 7 times(Number of Is) and anything stop.I don't know what to do.
Please help me.
Ok, I did it with just 2 buttons and it worked :
var button1 = document.getElementById("button1");
var button2 = document.getElementById("button2");
var startNext = false;
var y1 = 0;
var y2 = 0;
var interval1 = setInterval(function(){
y1++;
button1.style.top = y1 + "px";
if(y1>= window.innerHeight){
startNext = true;
return clearInterval(interval1);
}
},10);
var interval2 = setInterval(function(){
if(startNext){
y2++;
button2.style.top = y2 + "px";
if(y2 >= window.innerHeight){
return clearInterval(interval2);
}
}
},10);
<!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>
<link rel="stylesheet" href="index.css">
</head>
<body id="body" style="position: relative;">
<button id="button1" style="position: absolute;">graege</button>
<button id="button2" style="position: absolute;">ges</button>
</body>
<script src="index.js"></script>
</html>

dynamically added div not appearing

I'm trying dynamically add a div to a page. This is in Chrome. I've looked at several instructions pages. Seems like this should work, but no joy. I added style attributes that would make it obviously apparent, just to get started. The code is executed, per "Inspect", but no element is appearing. Also the element does not show up in "Inspect/Elements/Find".
function CreateDragClone(partType) {
var cloneContainer = document.createElement("div");
cloneContainer.setAttribute("id", "cloneDiv");
//cloneContainer.setAttribute("class", "closeContainer");
cloneContainer.style.visibility = "visible";
cloneContainer.style.position = "absolute";
cloneContainer.style.borderStyle = "solid";
cloneContainer.style.borderColor = "red";
cloneContainer.style.borderWidth = "1px";
cloneContainer.style.top = "200px";
cloneContainer.style.left = "200px";
cloneContainer.style.zIndex = "100000";
document.body.append(cloneContainer);
}
With this code you should get a little red dot representing de borderWidth;
Your code is almost done, you just forgot to add width and height to the div element, on the other hand, camelCase shouldn't have the first letter in uppercase.
(function createDragClone() {
const cloneContainer = document.createElement("div");
cloneContainer.setAttribute("id", "cloneDiv");
cloneContainer.style.visibility = "visible";
cloneContainer.style.position = "absolute";
cloneContainer.style.borderStyle = "solid";
cloneContainer.style.borderColor = "red";
cloneContainer.style.borderWidth = "1px";
cloneContainer.style.top = "200px";
cloneContainer.style.left = "200px";
cloneContainer.style.width = "200px";
cloneContainer.style.height = "200px";
cloneContainer.style.zIndex = "100000";
document.body.append(cloneContainer);
})();
<!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>
</head>
<body>
<div></div>
</body>
</html>
You need to specify height and width to the created element.
One more thing, partType is passed as an argument but not being used, so you can remove it.
function CreateDragClone() {
var cloneContainer = document.createElement("div");
cloneContainer.setAttribute("id", "cloneDiv");
//cloneContainer.setAttribute("class", "closeContainer");
cloneContainer.style.visibility = "visible";
cloneContainer.style.position = "absolute";
cloneContainer.style.borderStyle = "solid";
cloneContainer.style.borderColor = "red";
cloneContainer.style.borderWidth = "1px";
cloneContainer.style.top = "200px";
cloneContainer.style.left = "200px";
cloneContainer.style.zIndex = "100000";
cloneContainer.style.width = "100px";
cloneContainer.style.height = "100px";
document.body.append(cloneContainer);
}
CreateDragClone();

Return value of window.innerHeight seem to be wrong?

I am trying to get a viewport height size with window.innerHeight. But its return value seems to be wrong.
I tried window.outerHeight and window.innerHeight.
I added the viewport meta tag too.
<meta name="viewport" content="height=device-height; width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no">
console.log("viewport_inner_height: " + window.innerHeight);
console.log("viewport_outer_height: " + window.outerHeight);
and the result is:
viewport_inner_height: 2044
viewport_outer_height: 1047
window.outerHeight seem right.
How can I get exactly the viewport height by javascript?
window.innerHeight is right.
I found the code that gets exactly the viewport height by JavaScript.
Try to run the code following. Good luck.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="height=device-height; width=device-width; initial-scale=1.0; maximum-scale=1.0; user-scalable=no">
<title>Document</title>
</head>
<script>
console.log("viewport_inner_height: " + window.innerHeight);
console.log("viewport_outer_height: " + window.outerHeight);
</script>
<body>
<p class="dimensions">
<span id="w"></span>
×
<span id="h"></span>
</p>
</body>
<script>
!function(t,n,e){"undefined"!=typeof module&&module.exports?module.exports=e():t.verge=e()}(this,0,function(){var t={},e="undefined"!=typeof window&&window,n="undefined"!=typeof document&&document,o=n&&n.documentElement,r=e.matchMedia||e.msMatchMedia,i=r?function(t){return!!r.call(e,t).matches}:function(){return!1},u=t.viewportW=function(){var t=o.clientWidth,n=e.innerWidth;return t<n?n:t},c=t.viewportH=function(){var t=o.clientHeight,n=e.innerHeight;return t<n?n:t};function f(){return{width:u(),height:c()}}function l(t,n){return!(!(t=t&&!t.nodeType?t[0]:t)||1!==t.nodeType)&&function(t,n){var e={};return n=+n||0,e.width=(e.right=t.right+n)-(e.left=t.left-n),e.height=(e.bottom=t.bottom+n)-(e.top=t.top-n),e}(t.getBoundingClientRect(),n)}return t.mq=i,t.matchMedia=r?function(){return r.apply(e,arguments)}:function(){return{}},t.viewport=f,t.scrollX=function(){return e.pageXOffset||o.scrollLeft},t.scrollY=function(){return e.pageYOffset||o.scrollTop},t.rectangle=l,t.aspect=function(t){var n=(t=null==t?f():1===t.nodeType?l(t):t).height,e=t.width;return n="function"==typeof n?n.call(t):n,(e="function"==typeof e?e.call(t):e)/n},t.inX=function(t,n){var e=l(t,n);return!!e&&0<=e.right&&e.left<=u()},t.inY=function(t,n){var e=l(t,n);return!!e&&0<=e.bottom&&e.top<=c()},t.inViewport=function(t,n){var e=l(t,n);return!!e&&0<=e.bottom&&0<=e.right&&e.top<=c()&&e.left<=u()},t});
function updateViewport() {
var newHeight = verge.viewportH();
var newWidth = verge.viewportW();
document.getElementById('w').innerHTML = newWidth;
document.getElementById('h').innerHTML = newHeight;
}
// function updateScreenRes() {
// var newHeight = window.screen.height;
// var newWidth = window.screen.width;
// document.getElementById('screen_w').innerHTML = newWidth;
// document.getElementById('screen_h').innerHTML = newHeight;
// }
function doCalcs() {
requestAnimationFrame(updateViewport);
// requestAnimationFrame(updateScreenRes);
}
window.addEventListener('load', doCalcs, false);
</script>
</html>

Categories