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)
Related
I'm trying make simple game "Rock Paper Scissors". At this moment I got stuck in changing value of Global Variable. Situation: (for ex.) Click => [Rock]. I have to store this into Global Variable's ("playerMove").
const rock = document.createElement('button');
/*
*/
let playerMove;
playerMove = '';
I arleady try
rock.onclick = function() {
playerMove = 'Rock'; // Test in function..
}
but Its only work in function (Yea, we all know global variable doesn't work that way so..). I may be able to fix that problem soon but at this moment my mind can't think any better than this :|, I want help to find any good resource about this to (how) change textContent / Value of element by clicking on button.
Sorry for my bad English..
You can use HTMLButtonElement.addEventListener() to listen for "click" events, and then do whatever you want to, a simple demo
const btn = document.getElementById('test');
const container = document.getElementById('val');
btn.addEventListener('click', () => {
container.textContent = 'works'
})
<div id="val">test</div>
<button id="test">click me</button>
To update the playerMove variable you could use a function that set that value.
document.createElement('button');
const rock = document.querySelector('button');
let playerMove = ''
const updateMove = (move) => {
playerMove = move;
}
rock.onclick = () => {
updateMove('Rock');
}
const rock = document.getElementById('button');
console.log(rock)
let playerMove;
playerMove = '';
rock.addEventListener('click',(e)=>{
playerMove =e.target.innerHTML;
console.log(playerMove);
})
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title> Aide</title>
<link rel="stylesheet" href="index.css">
</head>
<body>
<header>
<button id="button">Rock</button>
<script type="text/javascript" src="index.js"></script>
</body>
</html>
strong text
This code works perfectly.
it takes the text that the button contains.
I think your mistake is that you didn't declare that the button you created a js is a child of body.
Ty guys
Well, I will explain lil more about what playerMove was doing..
playerText.textContent = playerMove;
so I simple was trying to change playerMove but after I see AnanthDev answer >>
function playerMove(element, move) {
element.addEventListener('click', () => {
playerText.textContent = move;
})
}
playerMove(rock, 'Rock');
playerMove(scissors, 'Scissors');
playerMove(paper, 'Paper');
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 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>
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 **/
}
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