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
Related
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 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 onmouseout and onmouseover events. Below code is working fine if i remove tags, what is confusing me is , with tags, only mouseover is firing and not mouseout. Please guide what i am doing wrong.
<!DOCTYPE html>
<html>
<body>
<div onmouseout="mouseout();" onmouseover="mouseover();" id="test"><h1> Mouse </h1> </div>
<div id="count"> </div>
<div id="count2"> </div>
<script>
var textonout = "<h1>Mouse out</h1>";
var count =0;
var out = 0;
var textonover = "<h1>Mouse Over</h1>";
function mouseout() {
document.getElementById("test").innerHTML = textonout;
document.getElementById("count2").innerHTML = out++;
}
function mouseover() {
document.getElementById("test").innerHTML = textonover;
document.getElementById("count").innerHTML = count++;
}
</script>
</body>
</html>
EDIT: Ok i think i understand my own question. In my case, onmouseout event doesnt fire if i have nested tags. I have tried the same code just replacing h1 tag with a div tag. I tried several combination (using span etc) as soon as i introduce any tag inside my first div, onmouseout stops working.
Can someebody guide me what is the issue ? i am not asking for the fix, i just want to understand the reason of this error.
EDIT(2). Another update, if i add the following lines, now the onmouseout event is triggering.
function mouseover() {
document.getElementById("test").innerHTML = textonover **+ count**;
document.getElementById("count").innerHTML = count++;
DEMO
Uncaught ReferenceError: mouseout is not defined
You had this error in your console. I admit, I prefer to seperate js and html. Call your events in your JS.
Additionally, you don't need to recreate an h1 everytime you want to change the text. Just add an id to your h1, and replace the text inside of it.
HTML:
<div id="test">
<h1 id="h1"> Mouse </h1>
</div>
<div id="count"></div>
<div id="count2"></div>
Javascript:
var h1 = document.getElementById('h1');
textonout = "Mouse out";
var count = 0;
var out = 0;
var textonover = "Mouse Over";
var test = document.getElementById("test");
test.onmouseout = mouseout;
test.onmouseover = mouseover;
function mouseout() {
h1.innerHTML = textonout;
document.getElementById("count2").innerHTML = out++;
}
function mouseover() {
h1.innerHTML = textonover;
document.getElementById("count").innerHTML = count++;
}
Follow this , it work perfect.
<!DOCTYPE html>
<html>
<body>
<h1 id="test"> Mouse </h1>
<div id="count"> </div>
<div id="count2"> </div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js" type="text/javascript"></script>
<script>
$(document).ready(function(){
var textonout = "Mouse out";
var count =0;
var out = 0;
var textonover = "Mouse Over";
$("h1").mouseover(function(){
$("h1").css("background-color","yellow");
document.getElementById("count").innerHTML = count++;
document.getElementById("test").innerHTML = textonover;
});
$("h1").mouseout(function(){
$("h1").css("background-color","lightgray");
document.getElementById("test").innerHTML = textonout;
document.getElementById("count2").innerHTML = out++;
});
});
</script>
</body>
</html>