Button Doesn't Work If Created Using innerHTML - javascript

I have this kind of structure
<button ng-click="something(1)">click!</button>
<div id="place"></div>
something() works in this situation, but if I try to make another button with innerHTML on a js code
str="<button ng-click=\"something(2)\">click 2!</button>"
document.getElementById("place").innerHTML = str;
thrn the 2nd button, the one created by innerHTML, apears normal, but doesn't call the function something() when clicked
Is there a nother way to add the button? the buttons should be generated proceduraly as the page runs
Thank you very much!

<script>
let btn = document.createElement("button");
btn.innerText = "click2"
// class
btn.classList = [];
// on click function
btn.onclick = () => {
}
document.getElementById("place").innerHTML = "";
document.getElementById("place").appendChild(btn)
</script>

Related

Javascript. Pressing button - call function

function greet () {
console.log ("Hi there!");
}
function addButton () {
document.createElement("[wanted_HTML_tag_here]");
}
There is separate HTML document. It has a button that calls the function addButton() upon being pressed. Said function has to create a new element and append it to the element. Pressing this new button has to call the function greet().
I try with [element_name].setAttribute("[attribute]", "[attribute_value]") but useless
Also trying document.[element_to_append_into].appendChild([element_being_added]); but same
Here's a complete working example (it is one way of doing it):
<html lang="en">
<body>
<button id="btn">Create Button</button>
</body>
<script>
function greet() {
console.log('Hi there')
}
function addButton() {
const button = document.createElement('button')
const buttonTextNode = document.createTextNode('Click')
button.appendChild(buttonTextNode)
button.onclick = greet
document.body.appendChild(button)
}
// get the button that creates other buttons
const buttonCreator = document.getElementById('btn')
buttonCreator.onclick = addButton
</script>
</html>

Why the button area is not working as I expected?

I am trying to make an auto scroll tool for the browser(Chrome). What i want is a button, so when i click the button, the page should auto scroll down. By the way, I am using an application, whenever i visit a website, the application will inject the script below in the website. Here is my script:
<script>
let btn = document.createElement("button");
var isScrolling = false;
btn.innerHTML = "start scroll";
btn.style.cssText = "width:50px;height:50px;float:right;background:grey;position:fixed;right:0;top:50%;opacity:0.5;border-radius:50%"
btn.addEventListener("click", () => onclick);
let autoScroll = () => {if(isScrolling){window.scrollBy(0, 1);setTimeout(autoScroll, 10)}};
onclick = function() {console.log("click"); isScrolling=!isScrolling; autoScroll()};
document.body.appendChild(btn);
</script>
The problem is when I click the other areas of the page(not the button area), it still will trigger the onclick function. What i want is the page only scroll down when i click the button area, not any other area of the page. Does anyone know where the problem is? You can copy and run the script in the chrome console, any help would appreciate!
The problem is that you are storing your onclick function into a global one, because you are not defining it before. This works correctly:
<script>
let btn = document.createElement("button");
var isScrolling = false;
const onclick = function() {console.log("click"); isScrolling=!isScrolling; autoScroll()};
btn.innerHTML = "start scroll";
btn.style.cssText = "width:50px;height:50px;float:right;background:grey;position:fixed;right:0;top:50%;opacity:0.5;border-radius:50%"
btn.addEventListener("click", onclick);
let autoScroll = () => {if(isScrolling){window.scrollBy(0, 1);setTimeout(autoScroll, 10)}};
document.body.appendChild(btn);
</script>
Pay attention that i'm defining the onclick before using it, and that it is directly used in addEventListener, you shouldn't return it in the arrow function:
// This is WRONG
btn.addEventListener("click", () => onclick);
// This is OK
btn.addEventListener("click", onclick);
I believe you are running into conflicts with your variables and the scripts already on the page. If injecting this script, you can break javascript code already on the page.
To get the variables into their own frame, try this:
<script>
(function () {
let btn = document.createElement("button");
var isScrolling = false;
btn.innerHTML = "start scroll";
btn.style.cssText =
"width:50px;height:50px;float:right;background:grey;position:fixed;right:0;top:50%;opacity:0.5;border-radius:50%"
let onclick = function() {console.log("click"); isScrolling=!isScrolling; autoScroll()};
btn.addEventListener("click", onclick);
let autoScroll = () => {if(isScrolling){window.scrollBy(0, 1);
setTimeout(autoScroll, 10)}};
document.body.appendChild(btn);
})();
</script>
The problem is in this line:
btn.addEventListener("click", () => onclick);
You would want either:
btn.addEventListener("click", onclick); // binding a reference for later execution
or
btn.addEventListener("click", () => onclick());
However, if you want to later btn.removeEventListener to prevent memory leaks, you would rather want the former variant
It would also be better code if you first declared the onclick handler and then bound it to button, not the other way around :)

pass click event between two page by localStorage

I want to take a click event from 2nd page . 1st page have a link for 2nd page, there have a button when click the button it add a HTML row on 1st page. I am trying to use localStorage for passing data. My code don't work, take a look below:
1st Page.html
HTML
<div id="content">
</div>
JS
var output = document.getElementById('content');
addEvent(window, 'storage', function (event) {
if (event.key == 'StorageName') {
output.innerHTML = event.newValue;
}
});
2nd Page.html
HTML
<input id="data" type="button" value="+" onclick="addRow()">
JS
addEvent(dataInput, 'keyup', function () {
localStorage.setItem('StorageName', this.value);
});
var dataInput = dataInput = document.getElementById('data');
object.onclick = function(){
addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
};
You haven't defined your addRow() function properly. A function's name is defined with the keyword function, not inside of the function body. Your code:
object.onclick = function(){
addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
};
Should be changed to:
function addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
}
object.onclick = addRow;
I agree with skyline3000's answer the addRow() should be defined. Also there are a few other things that could/should change:
define dataInput before attaching an event to it
object.onclick should be dataInput.onclick since thats the element being clicked. (is click event what you really want? maybe onkeyup?)
when you set the localStorage you want to set the function definition being passed to Page 1 which appears to be addRow(). Simply remove the parenthesis to pass just the definition.(Should also be defined before using)
If you want to just pass the function you shouldn't set the onclick event on Page 2. What you should probably do is record how many times you want it to run when you go to Page 1.
You dont need to pass the function everytime if it isnt changing; Just set it once and record the number of times it was clicked.
page 1 can catch the load event and the check localStorage for the function definition and number of times it was run. Then it can loop and perform the function.
the code you have doesn't add a link back to page 2 if thats what you are looking for but you can add that into the addrow function when you know the file name and path.
Page 1
var output = document.getElementById('content');
addEvent(window, 'load', function (event) {
if (localStorage.getItem('StorageName') && localStorage.getItem('rowsToAdd')) {
for(var i = 0; i > rowsToAdd;i++){
var addNewRow = localStorage.getItem('StorageName');
addNewRow();
}
}
});
Page 2
var dataInput = document.getElementById('data');
function addRow() {
var div = document.createElement('div');
div.className = 'row';
div.innerHTML = '<button>GO</button>';
document.getElementById('content').appendChild(div);
};
localStorage.setItem('StorageName', addRow);
dataInput.onclick = function() {
if(localStorage.getItem('rowsToAdd')){
localStorage.setItem('rowsToAdd', localStorage.getItem('rowsToAdd') + 1);
}else{
localStorage.setItem('rowsToAdd',1);
}
}
I didn't test this code so it may not work copy+pasted but something pretty close hopefully.
I also answered this with the best understanding of what you wanted that I could manage but I dont fully see the desired result of what you seemed to be doing.

Change image of button when pressed, using javascript

I am trying to set a value in variable when a specific button is pressed. I want this button to be in pressed state when i again reload the page. I am trying to check the value of variable in pageloaded function but i don't know that how can change the state of button in javascript. Pls help
HTML:
<button onclick="changeit()"><img src="bla.jpg" id="changevalue"></button>
JS:
function changeit(){
document.getElementById("changevalue").src = "newimg.jpg";
}
HTML:
<button id="myButton"><img src="myImage.jpg" id="myImage"></button>
JS:
var NEW_IMAGE_URI = "myNewImage.jpg";
var buttonState = false;
function changeButtonImage(){
if (buttonState) {
return;
}
document.querySelector("#myImage").src = NEW_IMAGE_URI;
buttonState = true;
}
document.addEventListener("DOMContentLoaded", function(event) {
var buttonElement = document.querySelector('#myButton');
buttonElement.addEventListener('click',changeButtonImage);
});

How do you dynamically display a button using JavaScript?

Below I have code where I am trying to dynamically create a button using Javascript (I don't want to just create a button with HTML) When I locally run the web page no button appears.
The buttonActionFunction is a separate function I have (that is fully working) where an image appears when the button is clicked.
Also how do I add to that code so that once the button is clicked that the button deactivates so they can't click it again?
<script>
function buttonFunction() {
var button= document.createElement("button");
button.appendChild(document.createTextNode("Click Me"));
button.onclick=buttonActionFunction();
document.getElementById("divId").appendChild(button);
}
buttonFunction();
</script>
function createButton(context, func) {
var button = document.createElement("input");
button.type = "button";
button.value = "Click Me";
button.onclick = func;
context.appendChild(button);
}
function functienaam()
{
createButton(document.body, functienaam);
}
createButton(document.body, functienaam);
jsfiddle : https://jsfiddle.net/fv42orad/1/
Add <div id="divId"></div> to your html
As for disabling the button on click
function buttonActionFunction(e) {
e.target.disabled = true
}
and button.onclick=buttonActionFunction; not
button.onclick=buttonActionFunction();
Based on #lordKain answer I've updated the code to disable the previous button when it is clicked, as shown bellow:
function createButton(context){
var button = document.createElement("input");
button.type = "button";
button.value = "Click Me";
button.onclick = function() {functienaam(button)};
context.appendChild(button);
}
function functienaam(button)
{
createButton(document.body);
button.disabled = true;
}
createButton(document.body);
https://jsfiddle.net/5unLc5xr/

Categories

Resources