How to add an ID onto a created element in JavaScript? - javascript

My original question was marked falsely by another user as a duplicate but the link provided did not answer any parts of the question asked so I will ask another. Making the site builder I ran into an issue where the prompt value when pressing okay is not used as the text in the created h1. Why is this? The class applies and creates all the elements I wanted to but the text is not present on the site at all, and there are no errors in the code because it all works fine.
.new-hd {
position: fixed;
z-index: 5;
bottom: 0;
right: 0;
}
.new-para {
position: fixed;
z-index: 5;
bottom: 0;
left: 0;
}
.classic-hd {
max-width: 100vw;
width: 100vw;
max-height: 15vh;
height: 15vh;
position: absolute;
left: 0;
top: 0;
background-color: black;
display: flex;
align-items: center;
}
#classic-hd-txt {
color: white;
font-family: sans-serif;
text-indent: 3vw;
}
.fa-times {
color: white;
position: absolute;
top: 0.25vh;
right: 1vw;
z-index: 5;
}
<!DOCTYPE html>
<html>
<head>
<title>Make a Site</title>
<script src="https://code.jquery.com/jquery-3.4.1.js"></script>
<link rel="stylesheet" href="path/to/font-awesome/css/font-awesome.min.css">
</head>
<body>
<button type="button" class="new-hd">
Make Header
</button>
<button type="button" class="new-para">
Make Paragraph
</button>
<script>
$(document).ready(function() {
$(".new-hd").click(function() {
var newHdTxt = window.prompt("What would you like your Header Text to be?", "Enter Response Here");
var newHdCont = document.createElement("header");
var newHd = document.createElement("h1");
$(newHdCont).addClass("classic-hd");
$(newHd).addClass("classic-hd-txt");
document.getElementsByClassName("classic-hd-txt").innerHTML = newHdTxt;
document.body.appendChild(newHdCont);
newHdCont.appendChild(newHd);
//alert(newTxt);
});
$(".new-para").click(function() {
document.createElement("p");
});
});
</script>
</body>
</html>

On behalf of Nik who gave the answer, here is the way you resolve this. Instead of using the DOM selector get.ElementsByClassName().innerHTML use the method newHd.innerText = newHdTxt.

use attr function to add id attribute.like this
$jqueryElement.attr('id', 'change_it_to_what_you_want_but_should_be_unique');

Related

Trying to access getElementById twice, but not working... but I've read I can, so something else must be wrong

I'm not well versed in JavaScript, so I'm probably not explaining this right, but I have a jsfiddle. I have a script that pops up a modal with another page in it. If I'm using one link all is well and everything works. It's perfect for what I need.
There are times when I want to add a second link with the same ID so that it pops up with the same functionality, same page and everything, but when I do that only the first link on the page works and the second link fails.
If I remove the first link, the second one works fine.
I would appreciate any thoughts on how to fix this so they both work.
HTML:
<p>
<a href="" id="link"
>Add your thoughts (this works, but the second link doesn't unless this
one is removed).</a
>
</p>
View or Add Comments<br />
<div id="popup"><iframe id="popupiframe"></iframe></div>
<div id="popupdarkbg"></div>
<p>(Click background to exit popup)</p>
JavaScript:
document.getElementById("link").onclick = function (e) {
e.preventDefault();
document.getElementById("popupiframe").src = "http://www.blankwebsite.com/"
document.getElementById("popup").style.display = "block";
document.getElementById("popupiframe").src =
"http://www.blankwebsite.com/";
document.getElementById("popupdarkbg").onclick = function () {
document.getElementById("popup").style.display = "none";
document.getElementById("popupdarkbg").style.display = "none";
};
CSS:
#comments {
width: 100%;
text-align: center;
margin: 15px 0 15px 0;
}
#popup {
display: none;
position: fixed;
top: 12%;
left: 15%;
width: 70%;
height: 80%;
background-color: white;
z-index: 10;
}
#popup iframe {
width: 100%;
height: 100%;
border: 0;
}
#popupdarkbg {
position: fixed;
z-index: 5;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: hidden;
background-color: rgba(0, 0, 0, 0.75);
display: none;
}

Advance slideshow without reloading page

My slideshow script uses the onclick event window.location.reload() to advance to the next mini-slideshow, causing the page to flicker when the “NEXT Plant” button is clicked.
Ideally, the onclick event should trigger a function to advance the slideshow, eliminating the need to reload the page.
Creating such a function, unfortunately, is easier said than done.
Intuitively, my first thought was to forego the onclick event window.location.reload() method and instead have the onclick event call the onLoad function runShow(), thinking that re-invoking this script would advance the slideshow. It didn’t.
Re-invoking other functions also failed to advance the slideshow, and now I’m out of ideas what to try next.
Please advise. Thanks.
body {
display: flex;
justify-content: center;
text-align: center;
background-color: black;
}
img {
display: block;
position: relative;
top: 20px;
max-width:100%;
max-height:calc(100vh - 160px - ((.4em + .6vmin) + (.4em + .6vmax)));
object-fit: contain;
}
.caption {
position: absolute;
bottom: 120px;
font-size: calc((.4em + .6vmin) + (.4em + .6vmax));
color: white;
left: 0;
right: 0;
width: 100%;
text-align: center;
}
p {
position: absolute;
bottom: 10px;
left: 0;
right: 0;
width: 100%;
text-align: center;
}
.button {
border-radius: 8px;
background-color: green;
border: none;
color: black;
padding: 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title>Plant Slideshow</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
</head>
<body onLoad="runShow()">
<img id="slide" onmouseover="stopShow()" onmouseout="runShow()" src="" alt="">
<script>
var genusSpecies={"Adam's Needle (Yucca filamentosa)":["Adam's Needle (Yucca filamentosa)1.jpg"],"Virginia Wild Rye (Elymus virginicus)":["Virginia Wild Rye (Elymus virginicus)1.jpg","Virginia Wild Rye (Elymus virginicus)2.jpg"]};
if (window.innerHeight > 1000) {
var specificResolution="./plants1220/"; // Higher-resolution photos for desktops
} else {
var specificResolution="./plants500/"; // Lower-resolution photos for smartphones
}
var curimg=0;
var keys=Object.keys(genusSpecies); // Creates array of keys
var plantNumber=Object.keys(genusSpecies).length;
x=Math.floor(Math.random() * (plantNumber)); // Selects random index number for “keys” array, the element’s value providing a named key for “genusSpecies”
var plant=genusSpecies[keys[x]]; // Value of named key (image file names of specific mini-slideshow)
function swapImage()
{
document.getElementById("slide").setAttribute("src",specificResolution+plant[curimg])
curimg=(curimg<plant.length-1)? curimg+1 : 0; timer = setTimeout("swapImage()",4000);
}
function stopShow()
{
clearTimeout(timer);
}
function runShow()
{
swapImage();
}
</script>
<div class="caption">
<script>
document.write(keys[x]); // Displays caption
</script>
</div>
<p><button class="button" onclick="window.location.reload()">NEXT Plant<br>(hover over slideshow to pause)</button></p>
<!-- Reloads page, advancing the slideshow, but is inefficient & causes flickering -->
</body>
</html>
Took a bit of doing to learn how it works.. and because of that I just made a function nextSlide that resets JUST the important stuff(you might wanna do something else other than random though) because your other functions do the rest :D
Pure random next slide makes there be several occurrences of the same slide being loaded.. If you want it not like that(eg: sequentially looping through array) just tell me in the comments, but as for now, your code runs without reloading
EDIT: IT WORKS PERFECTLY, WHAT IS GOING WRONG?
https://repl.it/talk/share/Testing/121825 has code forked from your repl(and I applied my below answer to it) and https://slideshow-code-needs-improving--paultaylor2.repl.co/ would let you see the full tab example(it works, and changes the images).. so I ask, what problems are you experiencing?
I did see one thing, that the value specificResolution are 2 different things from when you gave your snippet in your question and the snippet you have in your repl.. so just ensure that specificResolution checks EXISTING FOLDERS
//place this in a script tag SOMEWHERE AT THE BOTTOM LIKE BELOW BODY
var genusSpecies={"Adam's Needle (Yucca filamentosa)":["Adam's Needle (Yucca filamentosa)1.jpg"],"Virginia Wild Rye (Elymus virginicus)":["Virginia Wild Rye (Elymus virginicus)1.jpg","Virginia Wild Rye (Elymus virginicus)2.jpg"]};
/*HELLO, PLEASE MAKE SURE THIS VARIABLE HAS A VALID BEGINNING, since your example in the repl for this variable is DIFFERENT to the example I'm replicating from your question*/
/////////////////////////////////////////////////
if (window.innerHeight > 1000) {
window.specificResolution="./plants1220/"; // Higher-resolution photos for desktops
} else {
window.specificResolution="./plants500/"; // Lower-resolution photos for smartphones
}
/////////////////////////////////////////////////
var curimg=0;
var keys=Object.keys(genusSpecies); // Creates array of keys
var plantNumber=Object.keys(genusSpecies).length;
var rand=()=>Math.floor(Math.random() * (plantNumber));
var x=rand(); // Selects random index number for “keys” array, the element’s value providing a named key for “genusSpecies”
var plant=genusSpecies[keys[x]]; // Value of named key (image file names of specific mini-slideshow)
function swapImage()
{
document.getElementById("slide").setAttribute("src",specificResolution+plant[curimg])
curimg=(curimg<plant.length-1)? curimg+1 : 0; window.timer = setTimeout(swapImage,4000);
}
function stopShow()
{
clearTimeout(timer);
}
function runShow()
{
swapImage();
}
function nextSlide(){ //your other functions do the rest of work :D
x=rand(); curimg=0;
stopShow(); runShow();
plant=genusSpecies[keys[x]];
document.getElementsByClassName('caption')[0].innerText=(keys[x]);
}
document.getElementsByClassName('caption')[0].innerText=(keys[x]); // Displays caption
body {
display: flex;
justify-content: center;
text-align: center;
background-color: black;
}
img {
display: block;
position: relative;
top: 20px;
max-width:100%;
max-height:calc(100vh - 160px - ((.4em + .6vmin) + (.4em + .6vmax)));
object-fit: contain;
}
.caption {
position: absolute;
bottom: 120px;
font-size: calc((.4em + .6vmin) + (.4em + .6vmax));
color: white;
left: 0;
right: 0;
width: 100%;
text-align: center;
}
p {
position: absolute;
bottom: 10px;
left: 0;
right: 0;
width: 100%;
text-align: center;
}
.button {
border-radius: 8px;
background-color: green;
border: none;
color: black;
padding: 10px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 16px;
cursor: pointer;
}
<!DOCTYPE html>
<html>
<head>
<title>Plant Slideshow</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="styles.css">
</head>
<body onLoad="runShow()">
<img id="slide" onmouseover="stopShow()" onmouseout="runShow()" src="" alt="">
<div class="caption"></div>
<p><button class="button" onclick="nextSlide()">NEXT Plant<br>(hover over slideshow to pause)</button></p>
<!-- Reloads page, advancing the slideshow, but is inefficient & causes flickering -->
</body>
</html>

How do I loop multiple scripts in javascript?

I have some code here and I want the squares to go blue, green, indigo then go back to the beginning. Each time I click the button the colour will change. The code here goes blue, green, indigo and then changes between indigo and black while I want it to go to blue again. Is there a way of restarting the entire code again?
<--code for animated squares!-->
<!DOCTYPE html>
<html>
<style>
#container {
width: 400px;
height: 400px;
position: relative;
background: Black;
}
div#animate {
width: 50px;
height: 50px;
position: absolute;
left: 175px;
top: 0px;
background-color: Blue;
}
</style>
<style>
#containertwo {
width: 400px;
height: 400px;
position: relative;
background: Black;
}
div#animatetwo {
width: 50px;
height: 50px;
position: absolute;
left: 175px;
top: 175px;
background-color: Black;
}
</style>
<body>
<style>
#containerthree {
width: 400px;
height: 400px;
position: relative;
background: Black;
}
div#animatethree {
width: 50px;
height: 50px;
position: absolute;
left: 175px;
top: 350px;
background-color: Black;
}
</style>
<body>
<p>
<button onClick="button_click();button_clicktwo();button_clickthree()">Change Colour</button>
</p>
<div id ="container">
<div id ="animate"></div>
<div id ="animatetwo"></div>
<div id ="animatethree"></div>
</div>
<div id="box" onClick="button_click(j)();"></div>
<script>
var colors = ["Black","Black","Blue"];
function button_click() {
var box = document.getElementById("animate");
var background_color = box.style.backgroundColor;
var i = colors.indexOf(background_color);
if (i === colors.length-1) {
i = -1;
}
animate.style.backgroundColor = colors[i+1];
}
</script>
<div id="box" onClick="button_clicktwo();"></div>
<script>
var colorstwo = ["Green","Black","Black",];
function button_clicktwo() {
var box = document.getElementById("animatetwo");
var background_color = box.style.backgroundColor;
var i = colorstwo.indexOf(background_color);
if (i === colorstwo.length-1) {
i = -1;
}
animatetwo.style.backgroundColor = colorstwo[i+1];
}
</script>
<div id="box" onClick="button_clickthree();"></div>
<script>
var colorsthree = ["Black","Indigo","Black"];
function button_clickthree() {
var box = document.getElementById("animatethree");
var background_color = box.style.backgroundColor;
var i = colorsthree.indexOf(background_color);
if (i === colorstwo.length-1) {
i = -1;
}
animatethree.style.backgroundColor = colorsthree[i+1];
}
</script>
There's quite a bit of invalid and repetitive code, so for simplicity, I just reworked the entire thing. I'll note some of the problems below.
Since there were so many changes made to the HTML, CSS and JS, I won't list them all, but will leave it to you to observe the differences.
// Gather the colors and elements, and set a shared `i` to `0`
var colors = ["Blue", "Green", "Indigo"];
var elems = document.querySelectorAll(".animate");
var i = 0;
// Have a single function that makes the current element black and the next
// one a different color
function button_click() {
elems[i].style.backgroundColor = "Black";
if (++i === colors.length) {
i = 0
}
elems[i].style.backgroundColor = colors[i];
}
#container {
width: 400px;
height: 400px;
position: relative;
background: Black;
}
.animate {
width: 50px;
height: 50px;
left: 175px;
position: absolute;
}
.animate:nth-child(1) {
top: 0px;
background-color: Blue;
}
.animate:nth-child(2) {
top: 175px;
}
.animate:nth-child(3) {
top: 350px;
}
<p>
<button onClick="button_click();">Change Colour</button>
</p>
<div id="container">
<div class="animate"></div>
<div class="animate"></div>
<div class="animate"></div>
</div>
Note that there are other ways to do this too, like having each color set in the CSS, and then setting the visibility to hidden or visible with JavaScript.
Some of the general problems were:
the same ID attribute used more than once
an extra <body> tag
lots of repeating CSS, JS and HTML that was able to be greatly reduced

Change the background colour of a div when a certain div is showing

I have three divs for a Twitter post, a Facebook post and a LinkedIn post and these make up a carousel.
These are then inside of another div called #social-media-feeds.
I am wondering if it is possible to change the background colour of #social-media-feeds based on which div in the carousel is showing.
So when the twitter div shows I would like the background colour of #social-media-feeds to be #00aced, when the facebook div shows I would like the background colour to be #3b5998, and when the linkedin div shows I would like the background colour to be #007bb5.
If this is possible I'd really appreciate a hand. Thanks!
This is terribly formed code, but it works. I can't pretend to know what your code looks like so I hope this helps:
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
html, body {
height: 100%;
padding: 0px;
}
#social-media-feeds {
display: inline-block;
height: 100%;
width: 100%;
}
.post {
display: none;
}
#leftButton {
position: absolute;
top: 50%;
left: 0%;
height: 30px;
width: 60px;
text-align: right;
background-color: gray;
cursor: pointer;
}
#rightButton {
position: absolute;
top: 50%;
right: 0%;
height: 30px;
width: 60px;
background-color: gray;
cursor: pointer;
}
</style>
</head>
<body>
<div id="leftButton"><</div>
<div id="rightButton">></div>
<div id="social-media-feeds">
<div id="facebook" class="post">Facebook</div>
<div id="twitter" class="post">Twitter</div>
<div id="linkedIn" class="post">LinkedIn</div>
</div>
<script>
var socialMediaFeedsDiv = document.getElementById('social-media-feeds');
var backgroundColors = ["#3b5998", "#00aced", "#007bb5"];
var posts = document.getElementsByClassName('post');
var index = 0;
posts[index].style.display = 'inline-block';
socialMediaFeedsDiv.style.backgroundColor = backgroundColors[index];
var leftButton = document.getElementById('leftButton');
leftButton.addEventListener('click', function() {
posts[index].style.display = 'none';
index--;
if (index < 0) {
index = posts.length - 1;
}
posts[index].style.display = 'inline-block';
socialMediaFeedsDiv.style.backgroundColor = backgroundColors[index];
});
var rightButton = document.getElementById('rightButton');
rightButton.addEventListener('click', function() {
posts[index].style.display = 'none';
index++;
if (index > (posts.length - 1)) {
index = 0;
}
posts[index].style.display = 'inline-block';
socialMediaFeedsDiv.style.backgroundColor = backgroundColors[index];
});
</script>
</body>
</html>

JQuery replaced link not working under IE 8-10

I made a popup and I have a problem with IE 8-10 (under IE11 no problem). My code replace an image to linked image. Link is working under Firefox, Chrome and IE11, but not working under other IE versions. This is a popop window by default. Here is my code:
<div id="fadeinboxrevol">
<div id="koppbase">
<p class="kalapacs"><img src="./images/original.png" alt="Click here" /></p>
</div>
</div>
<script type="text/javascript">
var tto = jQuery.noConflict();
function get_path() {
var piclist =['./images/1.png','./images/2.png','./images/3.png','./images/4.png'];
var linklist =['1.html','2.html','3.html','4.html'];
var random = Math.floor(Math.random()*piclist.length);
var picpath = piclist[random];
var linkpath = linklist[random];
var pack = [picpath, linkpath];
return pack;
}
tto(".kalapacs").click(function () {
var mypack = get_path();
var mypic = mypack[0];
var mypath = mypack[1];
var content1 = '<p class="torp"><img class="torve" src="'+mypic+'" alt="Don't wait" /><a class="tortext" href="'+mypath+'"></a></p>';
tto("#koppbase").html(content1);
});
</script>
And here is my CSS:
#fadeinboxrevol {
position: absolute;
width: auto;
left: 301px;
top: 262.5px;
visibility: visible;
border: none;
background-color: ;
padding: 0 px;
z-index: 999;
text-align: left;
}
.kalapacs:hover {
cursor: url(http://cur.cursors-4u.net/others/oth-5/oth438.cur), progress !important;
}
.torp {
position: relative;
}
.tortext {
position: absolute;
width: 100%;
height: 100%;
left: 0;
top: 0;
display: block;
z-index: 9999;
}
#revolclosebutton {
margin-top: -40px;
right: 20px;
position: absolute;
width: 16px;
z-index: 999;
}
Here is an example in jsfiddle, I use jQuery 1.11 version for better compatibility:
http://jsfiddle.net/mykee/uDCKL/
I tried this line too:
tto("#koppbase").replaceWith(content1);
but not helped. :-(
What's my problem?
The problem is this line of code: var content1 = '<p class="torp"><img class="torve" src="'+mypic+'" alt="Don't wait" /><a class="tortext" href="'+mypath+'"></a></p>';
Change it to: var content1 = '<p class="torp"><a class="tortext" href="'+mypath+'"><img class="torve" src="'+mypic+'" alt="Don't wait" /></a></p>';
When you look at older IE the a is empty after the img tag, so its hard to click it! (Hover down the 2nd image.)
Demo: http://jsfiddle.net/uDCKL/7/
I found a solution! Changed content1 line to this:
var content = '<p class="torp"><a class="tortext" href="'+mypath+'"><img class="torve" src="'+mypic+'" alt="Dont wait" /></a></p>';
And CSS replaced with this and working:
.kalapacs:hover {
cursor: url(http://cur.cursors-4u.net/others/oth-5/oth438.cur), progress !important;
}
.torp {
position: relative;
}
.tortext {
display: block;
}
#revolclosebutton {
margin-top: -40px;
right: 20px;
position: absolute;
width: 16px;
z-index: 99999;
}

Categories