So I'm building a website where I create elements with javascript and give content to them stored in array that I get from database, which I was able to successfully accomplish. However, I want to not display the div parent that contains all other elements added through javascript when a user clicks on a button within the div that I want not to display. However, I noticed two problems that I want to figured out why it's worked as it is. First, when I click on the button, and I apply display none to its parent, it always applies display none on the last created div instead of the corresponding div parent of the element it was clicked. Also, even though the display none is applied to the last div (though like I said, I want it to apply display none to the parent of the clicked button), the last div is still displayed on the page though it's display is none.
I need help figuring out these two problems. Any help will be appreciated. Thanks. Btw, please don't mark duplicate because I did look up for similar problems but none of the solutions apply to the problem I'm having.
Here is the javascript code:
var j = 0;
for (var i = 0; i < array.length; i++) {
var mydiv = document.createElement('div');
var element = document.createElement('p');
var element2 = document.createElement('p');
var raiseRating = document.createElement('button');
var lowerRating = document.createElement('button');
var rating = document.createElement('h1');
var flag = document.createElement('button');
// Index is set to hold the id so it can be used to identify the quotations whose button was clicked
index[i] = array[i][j+3];
//raiseRating.id = "raiseRating";
raiseRating.innerHTML = "+";
// lowerRating.id = "lowerRating";
lowerRating.innerHTML = "-";
flag.innerHTML = "flag"
rating.innerHTML = array[i][j+2];
element.innerHTML = '\"' + array[i][j] + '\"';
element2.innerHTML = '\--' + array[i][j+1];
mydiv.appendChild(element);
mydiv.appendChild(element2);
mydiv.appendChild(raiseRating);
mydiv.appendChild(rating);
mydiv.appendChild(lowerRating);
mydiv.appendChild(flag);
if (document.body.appendChild(mydiv)) {
flag.addEventListener("click", function(){
console.log("this should print");
mydiv.style.display = "none";
//console.log(mydiv);
});
}
}
UPDATE: Here is the html since someone asked for it
<!doctype html>
<html lang="en">
<head>
<title>Quotation Service</title>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="style.css">
<link href="https://fonts.googleapis.com/css?family=Cookie"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Quicksand"
rel="stylesheet">
</head>
<body>
<div class="top-bar">
<h1>Quotes</h1>
<a href="register.php" >Register</a>
Login
Add Quote
</div>
</body>
</html>
I did not know what var array was so I just removed.This should point you in the right direction. The problem is your closures. I commented so you could notice. Read about them!
var j = 0;
for (var i = 0; i < 10; i++) {
var mydiv = document.createElement('div');
var element = document.createElement('p');
var element2 = document.createElement('p');
var raiseRating = document.createElement('button');
var lowerRating = document.createElement('button');
var rating = document.createElement('h1');
var flag = document.createElement('button');
// Index is set to hold the id so it can be used to identify the quotations whose button was clicked
//raiseRating.id = "raiseRating";
raiseRating.innerHTML = "+";
// lowerRating.id = "lowerRating";
lowerRating.innerHTML = "-";
flag.innerHTML = "flag"
mydiv.appendChild(element);
mydiv.appendChild(element2);
mydiv.appendChild(raiseRating);
mydiv.appendChild(rating);
mydiv.appendChild(lowerRating);
mydiv.appendChild(flag);
/** CLOSURE STARTS **/
(function(flag, node){
if (document.body.appendChild(node)) {
flag.addEventListener("click", function(){
console.log("this should print");
node.style.display = "none";
});
}
}(flag, mydiv));
/**CLOSURE ENDS **/
}
Related
I'm new to javascript (and I'm not allowed to use jQuery in class) and I'm struggling with onclick functions.
I want two separate sentences to turn green and the other one pink when I click on it so I gave both of them a different id.
for(var i = 0; i < content.length; i++){
var contentText = content[i];
var opening = document.createElement("p");
opening.id = "opening";
if(content[i].id ==="opening"){
opening.innerText = contentText.text;
}
textContainer1.append(opening);
document.getElementById("opening").onclick = function opening(){
document.getElementById("opening").style.color = 'green';
}
This is the first onclick function and it works like it should! But when I add the other sentence underneath:
for(var j = 0; j < content.length; j++){
var contentText2 = content[j];
var second = document.createElement("p");
second.className = "chapter-1";
second.id = "second";
if (content[j].id ==="second"){
second.innerText = contentText2.text;
}
textContainer2.append(second);
}
document.getElementById("second").onclick = function second(){
document.getElementById("second").style.color = 'pink';
}
The second one doesn't work anymore. I really can't figure out how to solve this and I need several ones in the same file. Can someone please help?
EDIT
I found out that it only works for the first thing in the json list, and not for the second, or third, etc. So I think I need a for loop to search within the elements, but I'm not sure how to do that in this case...
New answer
I think you've missed a } in the first bit of code.
for(var i = 0; i < content.length; i++){
var contentText = content[i];
var opening = document.createElement("p");
opening.id = "opening";
if(content[i].id ==="opening"){
opening.innerText = contentText.text;
}
textContainer1.append(opening);
}
document.getElementById("opening").onclick = function opening(){
document.getElementById("opening").style.color = 'green';
}
Old answer with probably better code
I may be misunderstanding you, but if you want your sentences to go green/pink when clicking on them, you just need the second function in each of your examples.
<p id="opening" onclick="opening();">opening</p>
<p id="second" onclick="second();">second</p>
<script>
var opening = function() {
document.getElementById("opening").style.color = "green";
}
var second = function() {
document.getElementById("second").style.color = "pink";
}
</script>
This makes opening go green when one clicks it and second go pink when one clicks it.
Alternatively, if you want to assign it without adding onclick in HTML:
document.getElementById("opening").onclick = function() {
document.getElementById("opening").style.color = "green";
}
document.getElementById("second").onclick = function() {
document.getElementById("second").style.color = "pink";
}
I have a group of images in my HTML with the ID's "Hole#" ex: "Hole1", "Hole2" ... "HoleN". These IMG tags are loading a locally stored image. My goal is to print an alert when one of the images is clicked.
I found another StackOverflow question that I thought would answer my question. I've incorporated it into my code below. Unfortunately it did not achieve the desired effect.
//Dynamically creates images
for (let i = 1; i <= NUM_HOLES; i++) {
let HoleID = `"hole${i}"`;
let HoleIDPic = `"holePic${i}"`;
holesString +=
`<div id=`+ HoleID + `>
<img id=` + HoleIDPic + ` src="" />
</div>`
}
window.onload = function() {
document.getElementById("img[id|=hole]").onclick = function()
{
alert("Clicked");
};
};
HTML:
<section id="holes">
</section>
replacing the code "img[id|=hole]" with "hole1" does work however (for hole1), So I've concluded its my syntax the ID selection.
The whole idea of using similar ids on all images is the wrong approach.
Use a common CSS class instead. Then, to find out which image was clicked, use a single delegate listener and make use of the event object that is automatically passed to your click handler. I'm showing you an example with buttons instead of images:
const buttonDiv = document.querySelector('.buttons');
// lets add some buttons
for (let i = 0; i < 5; i++) {
let button = document.createElement('button');
button.type = 'button';
button.className = 'button';
button.textContent = 'Button Number ' + i;
buttonDiv.appendChild(button);
}
// now let's add a delegate click listener on the div containing the buttons
buttonDiv.addEventListener('click', function(event) {
// in any event listener, the event object has a `target` property, telling you which element the event was raised on
// this allows us to only react in the click listener if the clicked element meets certain conditions
if (event.target.matches('button.button'))
console.log('you clicked on ' + event.target.textContent);
})
.buttons {
background-color: #f0f0f0;
padding: 10px;
}
<div class="buttons"></div>
Try this
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<section id="holes"></section>
<script>
loadImages(2);
function loadImages(NUM_HOLES){
const sectionHoles = document.getElementById('holes');
//Dynamically creates images
for (let i = 1; i <= NUM_HOLES; i++) {
let HoleID = `hole${i}`;
let HoleIDPic = `holePic${i}`;
let div = document.createElement('div');
let img = document.createElement('img');
div.id = HoleID;
img.id = HoleIDPic;
img.src = "someimage.png";
// put image element in div
div.appendChild(img);
// put div in section
sectionHoles.appendChild(div);
// adding event listener to the img element
document.getElementById(HoleIDPic).addEventListener('click', function(){
alert(HoleIDPic + 'clicked');
});
}
}
</script>
</body>
</html>
I have some input type=button which are created dynamically using JavaScript. Here I need to shift those clockwise while click on button. Here is my code:
<!-- Enter your HTML code here -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Buttons Grid</title>
</head>
<body>
<div id="btns" style="width:75%;">
</div>
<script>
for(var i=0;i<9;i++){
var index=i+1;
var element = document.createElement("input");
element.type = "button";
element.value = index;
element.id = "btn"+index;
element.setAttribute("style","width:30%;height:48px;font-size:24px");
var foo = document.getElementById("btns");
//Append the element in page (in span).
foo.appendChild(element);
}
document.getElementById("btn5").onclick=function(){
}
</script>
</body>
</html>
Here I need when user will click one button 5 the buttons present around button5 will move clockwise means button4 will shift to first place without changing its ids.
Something like this?
let container = document.querySelector("#btns");
container.insertBefore(container.lastElementChild, container.firstElementChild);
// or this ?
// container.appendChild(container.firstElementChild);
I suppose you don't need to create the buttons in js. You can create in html code. And just play with innertext of btns. My approach was like this;
btn5.addEventListener('click', () => {
const textofBtn = btn1.innerText;
btn1.innerText = btn4.innerText;
btn4.innerText = btn7.innerText;
btn7.innerText = btn8.innerText;
btn8.innerText = btn9.innerText;
btn9.innerText = btn6.innerText;
btn6.innerText = btn3.innerText;
btn3.innerText = btn2.innerText;
btn2.innerText = textofBtn;
});
but I saw another solution looking like more elegant here is you can check;
let nums=[1,2,3,6,9,8,7,4];
const ids=[1,2,3,6,9,8,7,4];
let btn5=document.getElementById("btn5");
btn5.onclick=function() {
nums.unshift(nums.pop());
for (i=0; i<=7; i++) {
document.getElementById("btn"+ids[i]).innerHTML=nums[i];
}
}
// writed by mark_russellbro1(hackerrank username)
I am trying to make a dynamic program that will insert some number of buttons, and perform some action onClick.
So far, for my test example, I took 5 as a number of buttons and some message as event that will happen onClick. Problem is there is not any change when I click on any of buttons.
Here is my HTML code:
<html>
<head>
<script src="C:\Users\milosn\Desktop\addlevel.js" type="text/javascript"></script>
</head>
<body id="ide" onload="retrieveMultipleRecords()">
<p id="ha">text</p>
</body>
</html>
And this is JS:
function retrieveMultipleRecords() {
var d = document.createElement('div');
for (var i = 0; i < 5; i++) {
var b = document.createElement('BUTTON');
var t = document.createTextNode('TEXT');
t.id = 'tek';
b.appendChild(t);
b.addEventListener("click", func);
d.appendChild(b);
var br = document.createElement("br");
d.appendChild(br);
}
document.body.appendChild(d);
function func() {
document.getElementById("ha").InnerHTML = "some other text";
}
}
Thanks in advance
I set up an e-commerce website for a friend using javascript and html, and with the nearlyfreespeech hosting service. I have made sure to load the html page correctly, and there are no errors (in both the console and on the actual page). I have also tried with both the javascript embedded in the html, and with 2 seperate files, but neither works. I am using no external libraries either. I added alerts for when the page loads, but nothing showed up. The page constructor is hooked up to the page via the onload event set on the body tag. I have tried it with Firefox, Google Chrome, and Internet Explorer, but neither worked. When I moved the creation of the controls into the html, the controls were there (meaning that the html is working), but the alerts still didn't show (signifying that the javascript is either being omitted or that the onload event is not being fired). Here is the code:
<!DOCTYPE HTML>
<html>
<head>
<title>GetLost</title>
<script type="text/javascript">
function loadcontrols()
{
var items = ["Green cuff", "Red cuff"];
var prices = ["20.00", "30.00"];
var colors = ["Green", "Red"];
var urls = ["http://media-cache-ak0.pinimg.com/736x/0f/f8/11/0ff811addad9b0165263eb73ba9806f0.jpg", "http://www.opalona.com/images/produits/big/big_2049-3.jpg"];
var controls = [];
for(var i = 0; i < items.length; i++)
{
var item = new loaditem(items[i], prices[i], colors[i], urls[i]);
controls.concat(item);
}
alert("All items loaded.")
}
function loaditem(name, value, color, imageUrl)
{
this.name = name;
this.value = value;
this.color = color;
this.imageUrl = imageUrl;
var container = document.CreateElement("div");
container.style.height = "300px";
container.style.width = "200px";
container.style.backgroundColor = color;
scroller.appendChild(container);
var image = document.CreateElement("img");
image.style.height = "220px";
image.style.witdh = "180px";
image.setAttribute("src", imageUrl);
container.appendChild(image);
var name = document.CreateElement("h4");
name.innerHTML = name + " for $" + value;
container.appendChild(name);
alert("The product " + name + "has been loaded.")
}
</script>
</head>
<body onload="loadcontrols">
<h1><b>Choose a product, and click on it to open it.</b></h1>
<div style="overflow-x: scroll" name="scroller" height="310px" width="650px"></div>
</body>
</html>
onload doesn’t take a function name; it takes some JavaScript code to run. If you had a single line of JavaScript code just referencing a variable:
loadcontrols
Then, well, nothing happens. If you want to call it, you need parentheses:
loadcontrols()