Selecting ID based on substring - javascript

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>

Related

Why won't the click listener log the user clicking on the div for the first time but does log every other time?

Background information: I'm dealing with many divs and recording the data-id of the particular div that user has clicked on.
I'm not sure why the click listener doesn't log the very first time I click on a div but it does log every other time.
For example, if I navigate to the page and click on a div, the data-id doesn't get logged at all.
But when I click on another div, it does get logged. If I keep clicking on another div, it does get logged, and so on.
How can I fix it so that whenever I navigate to the page for the first time and click on a div, the data gets logged?
Here's my JS code:
let img = document.getElementsByClassName('item');
let userClicked = function () {
let attribute = this.getAttribute("data-id");
console.log("clicked " + attribute);
}
for(let i = 0; i < img.length; i++) {
img[i].addEventListener('click', userClicked, false);
}
In my view problem is somewhere else. Try checking if any other element overlaps or your JS is loading at right time. You can check sample code here. Paste it in separate html file and it will work perfectly file.
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta charset="utf-8" />
<title>Image</title>
<style>
div {
background-color:#eaeaea;
margin-bottom:5px;
}
</style>
</head>
<body>
<div data-id="1" class="item">1 </div>
<div data-id="2" class="item">2 </div>
<div data-id="3" class="item">3 </div>
<div data-id="4" class="item">4 </div>
<script>
let img = document.getElementsByClassName('item');
let userClicked = function () {
let attribute = this.getAttribute("data-id");
console.log("clicked " + attribute);
}
for (let i = 0; i < img.length; i++) {
img[i].addEventListener('click', userClicked, false);
}
</script>
</body>
</html>

Move the dynamically created buttons in clockwise using JavaScript

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)

Javascript: How to center multiple buttons that were created in Javascript using dynamically set CSS Style

I am trying to create a row of three buttons in Javascript using dynamically set CSS Style, but I am having difficulty trying to center the row of buttons in the middle of the page. This is with buttons that are currently not part of a div.
I have tried button.align = 'center'; with no success.
Here is the link to jsfiddle snippet.
HTML SKELETON
<head>
<meta charset="utf-8">
<title>Buttons</title>
</head>
<body>
<script>
</script>
</body>
</html>
JAVASCRIPT
var one, two, three;
function button(text) {
var button = document.createElement('button');
var buttonText = document.createTextNode(text);
button.appendChild(buttonText);
return button;
}
function buttonTest() {
one = button('one');
two = button('two');
three = button('three');
// put the buttons on page
document.body.appendChild(one);
document.body.appendChild(two);
document.body.appendChild(three);
}
buttonTest();
Link Here
var one, two, three;
function button(text) {
var button = document.createElement('button');
var buttonText = document.createTextNode(text);
button.appendChild(buttonText);
return button;
}
function buttonTest() {
one = button('one');
two = button('two');
three = button('three');
var divElem = document.createElement('div');
divElem.setAttribute('style', 'text-align:center;');
// put the buttons on page
//document.body.appendChild(one);
//document.body.appendChild(two);
//document.body.appendChild(three);
divElem.appendChild(one);
divElem.appendChild(two);
divElem.appendChild(three);
document.body.appendChild(divElem);
}
buttonTest();
A quick solution would be adding text-align : center to the body
var one, two, three;
function button(text) {
var button = document.createElement('button');
var buttonText = document.createTextNode(text);
button.appendChild(buttonText);
return button;
}
function buttonTest() {
one = button('one');
two = button('two');
three = button('three');
// put the buttons on page
document.body.appendChild(one);
document.body.appendChild(two);
document.body.appendChild(three);
}
buttonTest();
body {text-align: center;}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Buttons</title>
</head>
<body>
<script>
</script>
</body>
</html>

Javascript element.display = "none" still shows div

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 **/
}

Issue with event listener - JavaScript

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

Categories

Resources