How to delete elements created by CreateElement and AppendChild - javascript

[
// Calendar
var calendar = document.getElementById("calendar");
calendar.addEventListener("click",function(){
factbox.style.bottom = "70px";
factbox.style.transition = "0s";
calendar.style.transform = "rotateX(-50deg)";
calendar.style.transformOrigin = "bottom center";
var hotdogs = document.createElement("IMG");
hotdogs.src = "SVG/hotdog2.svg";
hotdogs.setAttribute = ("id", "hotdogs");
everywhere.parentNode.removeChild("hotdogs");
});
// Hotdog
var hotdog = document.getElementById("hotdog");
var everywhere = document.getElementById("everywhere");
var NumClick4 = 0;
hotdog.addEventListener("click",function(){
var hotdogs = document.createElement("IMG");
hotdogs.src = "SVG/hotdog2.svg";
hotdogs.setAttribute = ("id", "hotdogs");
everywhere.appendChild(hotdogs);
var x = Math.floor(( Math.random() * 450) + 800);
NumClick4++;
console.log(x + " " + NumClick4);
hotdogs.style.width = "200px";
hotdogs.style.left = x + "px";
if(NumClick4 == 1) {
factbox.style.bottom = "70px";
factbox.style.transition = "0s";
} else {
}
});
<div id="hotdog" class="">
<img src="SVG/hotdog2.svg" alt="hotdog">
</div>
<div id="everywhere"></div>
<div id="calendar">
<img src="SVG/calendar.svg" alt="calendar">
</div>
<div id="factbox">
</div>
enter image description here
Sorry if my code looks messy. So as shown on the image, I want the hotdogs on the sky, which were created by "CreateElement" and "AppendChild" method to disappear using "RemoveChild" method. For example, when I click other elements like "flag", I want the just the new "hotdogs" to disappear. I think I am not getting how it works. I would appreciate advice and tips.

Following line is wrong by 2 counts
everywhere.parentNode.removeChild("hotdogs");
You are trying to remove something which hasn't been added yet
You need to remove the Element rather than string
i.e.
everywhere.parentNode.removeChild(hotdogs);

Related

Put links in images that are located in <script>

I'm new to html, and I also have no idea how to work with js, so can I insert a link in multiple images inside of javascript of an html?
Here is a code that make the image change every time I refresh,
What I need to do is make these image clickable, and leading to another site
Preferably, I'd want to try to make it so that the js can lead to a code in html, so i can also add stuff such as height
<img src="3w.png" alt="car" height="333">
function random_imglink() {
var myimages = new Array()
myimages[1] = "1.png"
myimages[2] = "2.png"
myimages[3] = "3w.png"
myimages[4] = "4w.png"
var ry = Math.floor(Math.random() * myimages.length)
if (ry == 0)
ry = 1
document.write('<img src="' + myimages[ry] + '" border=0>')
}
random_imglink()
Arrays are 0 based so no need to force 1 when 0
Just change the HTML to be a link
It is recommended to not use document.write, so instead insert it into a container
I am using template literals to create the link and eventListener to see when the page has loaded
const myimages = ["1.png", "2.png", "3w.png", "4w.png"]
const links = ["page1.html","page2.html","page3.html","page4.html"];
function random_imglink() {
var ry = Math.floor(Math.random() * myimages.length)
return `<img src="${myimages[ry]}" height="333" border=0/>`;
}
window.addEventListener("DOMContentLoaded", function() {
document.getElementById("linkContainer").innerHTML = random_imglink();
});
<div id="linkContainer"></div>

How to make images appear randomly in Javascript?

I need to create a web page with a button that says "start game". When this button is clicked, 5 images I have downloaded (img1.png...img5.png) must appear randomly, one at a time, every half a second. Here is my code so far, any help would be greatly appreciated!
<html>
<head>
<script>
var rollImagesSchedule;
var rollImagesCounter;
function rollImagesAnimation(){
rollImagesCounter = 0;
rollImagesSchedule = setInterval(500);
}
function rollImages(){
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
rollImagesCounter = rollImagesCounter + 1;
if (rollImagesCounter == 10){
clearInterval(rollImagesSchedule);
}
}
</script>
</head>
<body>
<h1>Game</h1>
<button onClick="rollImagesAnimation()">Start frog game</button>
<br /><br />
<img id="display" style='width:200px; height:200px;'>
</body>
</html>
I think you're getting stuck with the way to use setInterval.
You can try to create a counter outside setInterval function, and nest all of your works inside of it. And the counter should be checked at the top.
function rollImages(){
var counter = 0;
var interval = setInterval(function () {
if (counter === 10) {
clearInterval(interval);
return;
}
var imageValue = Math.floor(Math.random() * 5) + 1;
var imageFile = "img" + imageValue + ".png";
var theImage = document.getElementById("display");
theImage.src = imageFile;
counter++;
}, 500);
}
Then, you can edit the way to catch event rollImages:
<button onClick="rollImages()">Start frog game</button>
My English is not very good, so I might misunderstand your question. Let me answer it according to what I understand.
Your requirement is to randomly display one of the five pictures every 500 milliseconds, right? If so, you can try this idea:
Put the src of 5 pictures into an array
var imageSrcs = ["image1","image2","image3","image4","image5"];
Every 500 milliseconds, execute the following function:
function rollImages(){
// Randomly generate a random number between 0-4
int index = Math.floor(Math.random() * 5) + 1;
var theImage = document.getElementById("display");
// Use random numbers as subscripts and take values from the array
theImage.src = imageSrcs[index];
}
You can store the images name files into an array and then setInterval a random number and assign the source of an img html element:
var list = [
"image1.jpg",
"image2.jpg",
"image3.jpg",
];
var i = 0;
function changeImgs() {
var imageValue = Math.floor(Math.random() * list.length - 1) + 1;
image.src = list[imageValue];
}
setInterval(function() {
changeImgs()
}, 2000);
window.onload = changeImgs;
<img id="image" class="size">

Trying to get multiple elements to load with random positioning

So I'm not super great at JS yet, but I found this code block that does exactly what I need it to do - takes an element and makes it's position random. The problem is this only works if I use getElementById, but I want to do this with about 12 different elements, not just the one.
Ive tried giving them all the same class and using getElementsByClassName, I've tried using querySelector, I've tried querySelectorAll - With each one of these examples the code either doesn't work, or it only works for the first element.
Markup:
<div id="1" class="rando">
<img src="someIMG" alt="logo" itemprop="image">
</div>
<div id="2" class="rando">
<iframe width="200" height="250" src="someURL" frameborder="0" ></iframe>
</div>
JS:
function getRandomPosition(element) {
var x = document.body.offsetHeight-element.clientHeight;
var y = document.body.offsetWidth-element.clientWidth;
var randomX = Math.floor(Math.random()*x);
var randomY = Math.floor(Math.random()*y);
return [randomX,randomY];
}
window.onload = function() {
var rpos = document.getElementsByClassName("rando");
rpos.setAttribute("style", "position:absolute;");
document.body.appendChild(rpos);
var xy = getRandomPosition(rpos);
rpos.style.top = xy[0] + 'px';
rpos.style.left = xy[1] + 'px';
}
I also tried putting these through a loop, but that didn't work either:
function getRandomPosition(element) {
var x = document.body.offsetHeight-element.clientHeight;
var y = document.body.offsetWidth-element.clientWidth;
var randomX = Math.floor(Math.random()*x);
var randomY = Math.floor(Math.random()*y);
return [randomX,randomY];
}
window.onload = function() {
var rpos = document.querySelector("#1, #2");
for (var i = 0; i < rpos.length; i++) {
rpos.setAttribute("style", "position:absolute;");
document.body.appendChild(rpos);
var xy = getRandomPosition(rpos);
rpos.style.top = xy[0] + 'px';
rpos.style.left = xy[1] + 'px';
}
}
Any help / direction is, as always, greatly appreciated!
thanks!
You almost had it. In your for loop you operate on the entire HTMLCollection rpos rather than each seperate element. For example what this line rpos.setAttribute("style", "position:absolute;"); does is run setAttribute for this collection of elements, rather than for each element in this collection we should run setAttribute. With a small adjustment you get this:
function getRandomPosition(element) {
var x = document.body.offsetHeight - element.clientHeight;
var y = document.body.offsetWidth - element.clientWidth;
var randomX = Math.floor(Math.random() * x);
var randomY = Math.floor(Math.random() * y);
return [randomX, randomY];
}
window.onload = function() {
const rpos = document.getElementsByClassName("rando");
for (let rpo of rpos) {
rpo.setAttribute("style", "position:absolute;");
document.body.appendChild(rpo);
var xy = getRandomPosition(rpo);
rpo.style.top = xy[0] + "px";
rpo.style.left = xy[1] + "px";
}
};
<div id="1" class="rando">
<img src="someIMG" alt="logo" itemprop="image">
</div>
<div id="2" class="rando">
<iframe width="200" height="250" src="someURL" frameborder="0" ></iframe>
</div>
<p class="rando">Test A</p>
<p class="rando">Test B</p>
<p class="rando">Test C</p>
In your first example, your getElementsByClassName returns an Array-like collection. Your rpos variable therefore contains something you need to loop over. Loop over rpos and it should work.
Alternatively, in your second example, querySelector only returns the first element corresponding to that selector, so not something you can loop over. Change this to querySelectorAll to get an iterable list.
EDIT: I just noticed your for loop as it stands won't work either. Don't forget that you need to manipulate each element in the list, not the list as a whole.
In the loop in the second example, you need to work on each individual item, something like:
window.onload = function() {
var rpos = document.querySelector("#1, #2");
for (var i = 0; i < rpos.length; i++) {
rpos[i].setAttribute("style", "position:absolute;");
document.body.appendChild(rpos[i]);
var xy = getRandomPosition(rpos[i]);
rpos[i].style.top = xy[0] + 'px';
rpos[i].style.left = xy[1] + 'px';
}
}```

I want to update an article every 5 minutes with javascript, can't get it to work

I'm have been trying to get a single article on my website and have it swtich to another article on interval. I'm using flask to scrape the arcile title,image and text from 3 different source. Then I render a template with those elements in a list.
See code:
#app.route('/test')
def hello_world():
offshorenergyfeed = feedparser.parse('https://feeds.feedburner.com/OffshoreEnergyToday?format=xml')
offshorewindfeed = feedparser.parse('http://feeds.feedburner.com/OffshoreWindNews?format=xml')
rechargefeed = feedparser.parse('http://www.rechargenews.com/rss/')
feedlinks = [offshorenergyfeed.entries[0]['link'],offshorewindfeed.entries[0]['link'],rechargefeed.entries[0]['link']]
artikel_tekst = []
artikel_titel = []
artikel_image = []
for link in feedlinks:
artikel = Article(link)
artikel.download()
artikel.parse()
artikel_tekst.append(artikel.text)
artikel_titel.append(artikel.title)
artikel_image.append(artikel.top_image)
return render_template('graph.html',
artikel_tekst = artikel_tekst,
artikel_titel = artikel_titel,
artikel_image = artikel_image,
)
Now I want to I want to display 1 article at the time and swtich it to another with an interval(lets say 5 minutes). For some reason I can only get it to work with the title switch. Text and Image won't switch with the given code:
<div id=newsarticle_container>
<h1 id='titel'>{{artikel_titel[0]}}</h1>
<img id=plaatje src="{{artikel_image[0]}}">
<div id='tekst'>{{artikel_tekst[0]}}</div>
</div>
<script>
var titles = ["{{artikel_titel[0]}}", "{{artikel_titel[1]}}", "{{artikel_titel[2]}}"];
var images = ["{{artikel_image[0]}}", "{{artikel_image[1]}}", "{{artikel_image[2]}}"];
var text = ["{{artikel_tekst[0]}}", "{{artikel_tekst[1]}}", "{{artikel_tekst[2]}}"];
var counter = 0;
var elem1 = document.getElementById("titel");
var elem2 = document.getElementById("plaatje");
var elem3 = document.getElementById("plaatje");
var inst = setInterval(change, 2000);
function change() {
elem1.innerHTML = titles[counter];
elem2.innerHTML = images[counter];
elem3.innerHTML = text[counter];
counter++;
if (counter >= titles.length) {
counter = 0;
}
}
</script>
Can someone please help me out. I have been struggeling on this for a long time. I think i'm close to the solution but maybe it's needs to be way different. Let me know.
Thanks in advance!
you have
<h1 id='titel'>{{artikel_titel[0]}}</h1>
<img id=plaatje src="{{artikel_image[0]}}">
<div id='tekst'>{{artikel_tekst[0]}}</div>
which should be
<h1 id='titel'>{{artikel_titel[0]}}</h1>
<img id='plaatje' src="{{artikel_image[0]}}">
<div id='tekst'>{{artikel_tekst[0]}}</div>
later in your code you have
var elem1 = document.getElementById("titel");
var elem2 = document.getElementById("plaatje");
var elem3 = document.getElementById("plaatje");
which should be changed to
var elem1 = document.getElementById("titel");
var elem2 = document.getElementById("plaatje");
var elem3 = document.getElementById("text");

Fading out in Javascript

Hey I'm new to javascript and I'm working on a small chat program right now.
I've got all the chatlogs (global& private and stuff..) but i want to add a button which can make (most of) the elements of these little 'clients' fade out and in, so that you dont have to see ALL of them at one time, just the ones you want.
The (relevant) code with the example element mess1:
h=0;
newroom = function (roomname) {
//create new container
var div = document.createElement('div');
div.className = 'container';
//new text input
var mess = document.createElement('input');
mess.type = 'text';
mess.id = 'mess1' + i;
div.appendChild(mess);
//minimizer button
var min = document.createElement('input');
min.type = 'button';
min.value = 'Minimize chat';
min.id = 'min' + i;
div.appendChild(min);
document.body.appendChild(div);
document.getElementById("min" + h).addEventListener("click", function (){
//this is where the magic happens
}
h++;
};
I've tried document.getElementById("mess1" + h).style.visibility = 'hidden';, but that just makes the element disappear, leaving a big ugly blank space behind.
I thought document.getElementById("mess1" + h).fadeOut('slow'); would fix that, but it just doesn't do anything...
Thanks in advance for your answers
function fadeout(element) {
var op = 1; // initial opacity
var timer = setInterval(function () {
if (op <= 0.1){
clearInterval(timer);
element.style.display = 'none';
}
element.style.opacity = op;
element.style.filter = 'alpha(opacity=' + op * 100 + ")";
op -= op * 0.1;
}, 50);
}
first of all I will recommend to use jQuery, it will make your life much more easy. In jQuery, you can fade the element and then remove it like this
$("#mess1" + h).fadeOut('slow',function(){
$("#mess1" + h).remove();
});
It will first fade the element and will then remove it from node if required
You can use
document.getElementById("mess1" + h).style.display= 'none';
it will hide element without empty space. But if you whant to hide element with animation you can use eq. this jquery:
$("#mess1" + h).hide('slow')
or eq. 'fast' - as parameter

Categories