Place new divs above / move old divs below - javascript

I have some toast notifications. I gave them a position "absolute" and want them to place themselves on their own.
New toasts should place themselves above the already existing ones. The old one would move down then.
So this is my important Div:
CreateWrapper(toastMessage, foreColor, borderColor, backgroundColorIconDiv, backgroundColorContentDiv) {
var wrapperDiv = document.createElement("div");
var width = 350;
wrapperDiv.id = "toast_" + this.toastCounter;
wrapperDiv.style.position = "absolute";
wrapperDiv.style.left = "50%";
wrapperDiv.style.display = "none";
wrapperDiv.style.width = width + "px";
wrapperDiv.style.height = "100px";
wrapperDiv.style.border = "2px solid " + borderColor;
wrapperDiv.style.borderRadius = "10px";
wrapperDiv.onclick = function() {
wrapperDiv.remove(); // Destroy the toast by clicking on it
}
document.body.appendChild(wrapperDiv);
}
and after creating it I use this code for some animations and destroying it:
var thisToast = this.toastCounter - 1; // get the toast Id
$(document).find("#toast_" + thisToast)
.fadeIn(750)
.delay(3000)
.fadeOut(750, function() {
$(this).remove(); // Destroy the toast
});
Here's a picture of what I am looking for

Check out this JSBIN.
You can use Bootstrap's grid system to make things a little easier.
You should never really use absolute layout, it makes responsive webpages impossible - take a look at what happens when you resize your browser.
You will want to have a look at the Element API.
var container = document.querySelector('div.container');
var newDiv = document.createElement('div');
newDiv.innerHTML = "HELLO WORLD";
container.prepend(newDiv);
And the accompanying HTML
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<script src="https://code.jquery.com/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
<script src="https://unpkg.com/#reactivex/rxjs#5.0.3/dist/global/Rx.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/expect/1.20.2/expect.js"></script>
<div class="container">
hey
</div>
</body>
</html>
The method you are looking for is prepend()

Related

I have multiple lines of text that print in typewriter animation. However, when I refresh my browser the different lines of texts get mixed up

I have multiple lines of text that print in typewriter animation, but when I refresh my browser the different lines of texts get mixed up.
Something like this "****eI icsr eAahtmeedr .t hWiesl cWoembes ittoe muys iWnegb sHiTtMeL,. CSS, and JS.**"
Click around Run snippet 5 or 6 times and including the code buttons, and you will see it see the problem.
The intro is a automatic animation when you first land the page which reads "Hello! My name is Frank. Welcome to my Website."
Tell Me More button prints out "I created this Website using HTML, CSS, and JS."
Nice! button prints out "This website is to showcase my skills."
Ok prints out "You should hire me. Scroll down to see why."
This is just a template. I am actually very new to Java and getting familiar with CSS and HTML. I am creating a portfolio and also learning to code, so bear with me.
I am basically trying to copy this website here https://www.amysboyd.com
I would like the buttons to disappear like in the website, but I don't know how to do that.
<!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>Portfolio</title>
<link rel="stylesheet" href="Portfolio Styles.css" </head>
<body>
<div class="abouttextsection">
<h1 id='output'></h1>
<script>
var a = 0;
var introtxt = 'Hello! My name is Frank. Welcome to my Website.';
var speed = 50;
function aboutintro() {
if (a < introtxt.length) {
document.getElementById("output").innerHTML += introtxt.charAt(a);
a++;
setTimeout(aboutintro, 50);
}
}
window.onload = aboutintro;
var doc, bod, I, TypeMaker; // for use on other loads
addEventListener('load', function() {
doc = document;
bod = doc.body;
I = function(id) {
return doc.getElementById(id);
}
TypeMaker = function(element, interval) {
this.element = element;
this.interval = interval || 50;
var t = this,
r;
this.type = function(string) {
if (r) clearInterval(r);
var s = string.split(''),
l = s.length,
i = 0;
var p = 'value' in this.element ? 'value' : 'innerHTML';
this.element[p] = '';
r = setInterval(function() {
t.element[p] += s[i++];
if (i === l) {
clearInterval(r);
r = undefined;
}
}, t.interval);
}
}
var typer = new TypeMaker(I('output')),
First_test = I('First_test'),
Second_test = I('Second_test'),
Third_test = I('Third_test');
var testArray = [''];
var testArrayL = testArray.length;
First_test.onclick = function() {
typer.type('I created this Website using HTML, CSS, and JS.');
}
Second_test.onclick = function() {
typer.type('This website is to showcase my skills.');
}
Third_test.onclick = function() {
typer.type('You should hire me. Scroll down to see why.');
}
});
</script>
<div class="aboutsectionbutton">
<button id='First_test' type='button' value='Tell Me More' />Tell Me More</button>
<button id='Second_test' type='button' value='Nice!' />Nice!</button>
<button id='Third_test'>Ok</button>
</div>
</div>
</body>
</html>
Add fadeOut transition to css class ->
CSS:
.hidden {
visibility: hidden;
opacity: 0;
transition: visibility 0s .25s, opacity .25s linear;
}
And on click event just add this class ->
JS:
Second_test.onclick = function() {
this.classList.add('hidden')
typer.type('This website is to showcase my skills.');
}
jsfiddle

How can i put it background image on setAttribute method?

I'm making a simple program that cuts the circle evenly.
enter image description here
and I want to put it image using 'setAttribute' method.
but, It doesn't work as i thought.
here is my code.
<!DOCTYPE html>
<html lang="kr">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{margin:0; padding:0;}
</style>
<script>
function elt(name, attributes){
var node = document.createElement(name);
if( attributes ){
for(var attr in attributes){
if(attributes.hasOwnProperty(attr)){
node.setAttribute(attr,attributes[attr]);
}
}
}
for(var i=2; i<arguments.length; i++){
var child = arguments[i];
if( typeof child == "string" ){
child = document.createTextNode(child);
}
node.appendChild(child);
}
return node;
}
window.onload=()=>{
const IMG_W_COUNT = 50;
const IMG_H_COUNT = 33;
const IMG_SUM = 1650;
for(var i=1,j=0;i<=IMG_SUM;i++,j+=18){
var ImageSaver = elt("div",{
class:"menu item"+i,
width:18+"px",
height:18+"px",
background:"url('paint.jpg')",
backgroundPosition:0+"px"+" "+j+"px"
});
document.body.appendChild(ImageSaver);
}
}
</script>
</head>
<body>
</body>
</html>
The elt function is a function that helps to easily generate an element.
I'd really appreciate your help.
background, height and width aren't attributes (except on a few elements, and there they are mostly deprecated), nor is backgroundPosition.
To set a CSS property value with a function use setProperty on a style declaration.
Make sure you use the CSS property name, which is background-position not backgroundPosition.
element.style.setProperty("name", "value");
You have to set CSS properties.
element.style.width=18+"px";
element.style.height=18+"px";
element.style.background="url('paint.jpg')";
element.style.backgroundPosition="top right";

highlight span tags inside div on onmouseup

I am trying to highlight individual spans inside my document body onmouseup. My trouble is that for some reason every element is highlighted by default and I can't seem to get it to work on window.getSelection(). I only need it to highlight the span when I've clicked it.
Would anyone know a quick way of doing this?
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The HTML5 Herald</title>
<meta name="description" content="The HTML5 Herald">
<meta name="author" content="SitePoint">
<link rel="stylesheet" href="./styles.css">
</head>
<body>
<h2>doc body</h2>
<div id="docbod" class="docbody"> </div>
<script src="./highlight.js"></script>
</body>
</html>
var documentbody = document.getElementById("docbod");
/* turns every word in the document into an element then appends them to the div that contains the doc body */
function splitdocintowords(div) {
var divarray = []
var state = ["hey", "there", "how", "are", "you", "doing?"]
for (let i = 0; i < state.length; i++) {
span = document.createElement("span")
span.textContent = state[i]
//-------^
span.id = "word" + i;
span.classList.add("textBackground")
span.addEventListener("onMouseup", highlight(span));
div.append(span);
div.append(" ");
}
}
splitdocintowords(documentbody);
/* highlights a selected word within the document*/
function highlight (element){
element.style.background='yellow';
console.log("selected element")
}
You have a mistake when adding event listener, the name of the event is 'mouseup'.
span.addEventListener("mouseup", () => span.style.background = 'yellow');

While True loop prevents page from loading

I apologise if my question seems simple, I am still trying to figure out JavaScript. I am building a website where I want the contents of a <p> to constantly change. I want it to loop over the contents of an array defined in my javascript code. However, when I put everything in a while (true) (because I want it to happen constantly), the <p> content never changes and the page is stuck on loading.
Here is the code I have so far:
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="about.css">
<meta charset="UTF-8">
<title>My Site</title>
</head>
<script>
function changeDynamicText() {
var descriptions = ['list', 'of', 'strings', 'to', 'loop', 'over'];
let i = 0;
while (true) {
window.setTimeout(function() {
document.getElementById("dynamicline").innerHTML = descriptions[i];
}, 600);
i = i + 1;
if (i >= descriptions.length) i = 0;
}
}
</script>
<body onload="changeDynamicText()">
<p id="dynamicline">Starting Text</p>
</body>
</html>
Help of any kind is greatly appreciated.
When you use while(true), it will block the JavaScript event loop and therefore no longer render the rest of the body.
You can achieve what you're trying to do by working asynchronously. You already did use setTimeout in there, but you could also use setInterval to trigger the method on a recurring basis.
function changeDynamicText() {
var descriptions = ['list','of','strings','to','loop','over'];
let i = 0;
setInterval(function () {
document.getElementById("dynamicline").innerHTML = descriptions[i];
i = i + 1;
if (i >= descriptions.length) i = 0;
}, 600);
}
You can use setInterval instead.
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="about.css">
<meta charset="UTF-8">
<title>My Site</title>
</head>
<script>
function changeDynamicText() {
var descriptions = ['list','of','strings','to','loop','over'];
let i = 0;
setInterval(() => {
document.getElementById("dynamicline").innerHTML = descriptions[i];
i = (i + 1) % descriptions.length;
}, 600)
}
</script>
<body onload="changeDynamicText()">
<p id="dynamicline">Starting Text</p>
</body>
</html>
You can easily do this with setInterval instead of setTimeout. Use setInterval when you need something to constantly do something in periods of time.
And I moved the i manipulation inside of the interval because you want that to execute each time the function gets called.
Also, it's just a really good habit to get into to put your script tags as the very last element of the body in the HTML document. This way you can ensure that all DOM content has loaded before attempting to manipulate the DOM.
Here is a JSFiddle with the code below: https://jsfiddle.net/mparson8/41hpLaqw/2/
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="about.css">
<meta charset="UTF-8">
<title>My Site</title>
</head>
<body onload="changeDynamicText()">
<p id="dynamicline">Starting Text</p>
<script>
function changeDynamicText() {
var descriptions = ['list','of','strings','to','loop','over'];
let i = 0;
let interval = window.setInterval(function () {
document.getElementById("dynamicline").innerHTML = descriptions[i];
i = i + 1;
if (i >= descriptions.length) i = 0;
}, 600);
}
changeDynamicText();
</script>
</body>
</html>
while (true) always blocks the page until it finishes using a break statement, in your code is never finishing, so what you need to do is call the function itself in the timeout (and make i a global variable to keep track of the array position)
let i = 0;
function changeDynamicText() {
var descriptions = ['list','of','strings','to','loop','over'];
setTimeout(function () {
document.getElementById("dynamicline").innerHTML = descriptions[i];
changeDynamicText()
}, 600);
i = i + 1;
if (i >= descriptions.length) i = 0;
}
loops are blockers infinite loops are infinite blockers. What you need is a time based switcher - a built in timeout functionality which you can call in a cyclical manner - or a, on interval ticker. Any of them will do...
function changeDynamicText() {
var descriptions =
['list','of','strings','to','loop','over'];
var i = 0;
setInterval( tick, 800 );
function tick( ) {
dynamicline.innerHTML = descriptions[ i++ ];
if(i >= descriptions.length-1 ) i = 0
}
}
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="about.css">
<meta charset="UTF-8">
<title>My Site</title>
</head>
<script>
</script>
<body onload="changeDynamicText()">
<p id="dynamicline">Starting Text</p>
</body>
</html>

why mouse coodrinates not showing up

i am learning javascript DOM . wrote this code , there was lots of errors in console . finally everything is sorted out. but the mouse coordinates are not showing . learning about addEventListener and using querySelector. where am i doing wrong. stuck on it since two days.
Here is the JSFiddle : https://jsfiddle.net/088a9at5/
<!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">
<title>MouseEvent</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h1 onmouseover="style.color='red'" onmouseout="style.color='black'">Mouse over this text</h1>
<div class="coordinateBox"></div>
<div class="result"></div>
<script src="script.js"></script>
</body>
</html>
.coordinateBox {
width: 400px;
height: 200px;
border: 2px solid black;
}
const RECT = document.querySelector(".coordinateBox");
const ANS = document.querySelector("result");
function mouseCoordinate(e) {
var x = e.clientX;
var y = e.clientY;
var coo = "X : " + x + " Y : " + y;
document.querySelector("result").innerHTML = coo
}
if(ANS){
ANS.onclick = mouseCoordinate;
}
Apart from corrrecting the selector name in querySelector to querySelector('.result'),
if you target the click on the element ANS it will never get fired because the element is of height and width 0;
Instead if you target RECT it works,
https://jsfiddle.net/088a9at5/4/
You were missing two . in .result and you need to create a listener on the rectangle, not on the result.
const RECT = document.querySelector(".coordinateBox");
const ANS = document.querySelector(".result");
function mouseCoordinate(e) {
var x = e.clientX;
var y = e.clientY;
var coo = "X : " + x + " Y : " + y;
document.querySelector(".result").innerHTML = coo
}
if(ANS){
RECT.onclick = mouseCoordinate;
}
.coordinateBox {
width: 400px;
height: 200px;
border: 2px solid black;
}
<h1 onmouseover="style.color='red'" onmouseout="style.color='black'">Mouse over this text</h1>
<div class="coordinateBox"></div>
<div class="result"></div>
You're missing the . in document.querySelector("result") which should be document.querySelector(".result").
The other major issue is that you haven't added an event listener.
RECT.addEventListener('mousemove', mouseCoordinate)
Here is your jsfiddle, which is now working.
Also, here is a very, simple codepen which illustrates the nuts and bolts.
P.S. In your jsfiddle, you haven't styled ANS, so it's hard to tell what you want the click event to be attached to? And for some reason it's not letting me style the .result element :/
Based on your fiddle
Because you just missed the class identifier . in this line
const ANS = document.querySelector("result"); before result
It should be like this
const ANS = document.querySelector(".result");
Same thing with document.querySelector("result").innerHTML = coo this line.
And provide some height and width to your result div and border too so you can see in which area you have to click.

Categories