Javascript onClick() event not working when used dynamically - javascript

I'm struggling to make the onclick event listener work in my results.
here is my code:
function createLink(text, parentElement) {
var a = document.createElement('p');
var linkText = document.createTextNode(text);
a.appendChild(linkText);
temp1 = text.replace("/","-");
temp2 = res1.replace("/","-");
a.onclick=function(){goMainMenuFromResults();};
parentElement.appendChild(a);
var br = document.createElement('br');
parentElement.appendChild(br);
}
The line in question is:
a.onclick=function(){goMainMenuFromResults();};
The function is present in another section but works in the hardcoded html events. I just can't make it work when its imported into the element in javascript.
Any help will be greatly appreciated!

James, it seems to work fine, just a var called res1 was getting error here. Take a look:
temp2 = res1.replace("/","-");
http://jsfiddle.net/MarcelKohls/23tBM/291/

I removed the lines containing variables that were not defined. I then added a call to preventDefault() on the event raised inside the event handler. And it now works fine. New elements are created and the click handler works on the new elements.
function createLink(text, parentElement) {
var a = document.createElement('p');
var linkText = document.createTextNode(text);
a.appendChild(linkText);
//temp1 = text.replace("/","-");
//temp2 = res1.replace("/","-");
a.onclick = function(e) {
e.preventDefault();
goMainMenuFromResults();
};
parentElement.appendChild(a);
var br = document.createElement('br');
parentElement.appendChild(br);
}

Related

Why isn't my function related to an onclick workin?

I'm studding HTML, CSS and JS and while I was creating an exercise, I was forced to stop due to an error. I created an button dynamically, setted an onclick to it and then created a function with that onclick. The problem is that the function isn't working, at leats it doesn't made anything till now.
let formularys = document.querySelector('section#formulary')
let slct = document.createElement('select')
let opts = document.createElement('option')
let optp = document.createElement('option')
let fbtn = document.querySelector('input#formularybtn')
let nbtn = document.createElement('input')
let br = document.createElement('br')
slct.id = 'pors'
slct.size = '2'
opts.value = 'rsite'
opts.innerHTML = 'Rate site'
optp.value = 'rp'
optp.innerHTML = 'Rate products'
nbtn.setAttribute('type', 'button')
nbtn.setAttribute('value', 'Next')
nbtn.setAttribute('onclick', 'nbutton')
function nbutton(){
console.log('Next working')
/*if(slct.selectedIndex == 1){
console.log('Valid rate choose')
}*/`enter code here`
}
instead of using setAttribute you can just do
nbtn.onclick = nbutton
in javascript, onclick isn't a string but a function.
The problem is, you are not appending your html code generated from JavaScript to DOM. You can either append to main DOM like below
document.body.appendChild(nbtn);
document.body.appendChild(optp);
or you can append them to some parent div by first getting div id
document.getElementById("divId").appendChild(nbtn);
where divId is id of your div where you want to add this html.
Also you should assign event listener in correct way as suggested by Tony and Rashed Rahat.
Try:
element.onclick = function() { alert('onclick requested'); };

Anchor dynamic element with click event

I am trying to dynamically add an anchor element through Javascript. The problem I have is the onclick event is not firing. I believe the problem is how I am generating the HTML. I am creating an array and then push my HTML code to the array. After I have created my output I am joining the array and then adding it to the div tag I have.
var itemLink = new Object();
itemLink.LinkName = "Edit User";
itemLink.LinkListClass = "";
itemLink.LinkListRole = "";
itemLink.LinkFunction = function() {
//do something specific with rowItem variable
alert(rowItem);
}
var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;
var output = [];
output.push('<table>');
output.push('<thead>');
output.push('<tr><th>col1</th><th>col2</th></tr>');
output.push('</thead>');
output.push('<tbody>');
output.push('<tr><td>col1 data</td><td>col2 data</td></tr>');
output.push('</tbody></table>')
var d1 = document.createElement('div');
d1.appendChild(aTag);
output.push(d1.innerHTML);
var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');
<div id="mainViewer"></div>
When I generate the output without the use of the array and joining of the output, the anchor element gets created and the onclick event works just fine.
Any ideas?
I will have multiple anchor links and I don't want to hardcode the function name. I want the onclick event to fire whatever function the itemLink Object has set.
What's the problem? You bind a function to a temp DOM element, then append its html, not its events (that's how innerHTML works). So when a link appended to the DOM, it's a different DOM link, so although the link looks the same it's not.
So, what is the solution? to push a DOM element instead of string, something like this:
//var itemLink = new Object();
//itemLink.LinkName = "Edit User";
//itemLink.LinkListClass = "";
//itemLink.LinkListRole = "";
//itemLink.LinkFunction = function() {
//do something specific with rowItem variable
//alert(rowItem);
//}
var itemLink = {
LinkName: "Edit User",
LinkListClass: "",
LinkListRole: "",
LinkFunction: function() {
//do something specific with rowItem variable
alert(rowItem);
}
};
var aTag = document.createElement("a");
aTag.setAttribute('class', 'btn btn-primary');
aTag.innerHTML = itemLink.LinkName;
aTag.setAttribute('href', '#');
var rowItem = 'abc1111'; //would be setting the rowId or some sort of identifier
aTag.onclick = itemLink.LinkFunction;
var output = [];
output.push('<table>');
output.push('<thead>');
output.push('<tr><th>col1</th><th>col2</th></tr>');
output.push('</thead>');
output.push('<tbody>');
output.push('<tr><td>col1 data</td><td>col2 data</td></tr>');
output.push('</tbody></table>')
var mainView = document.getElementById('mainViewer');
mainView.innerHTML = output.join('');
var d1 = document.createElement('div');
d1.appendChild(aTag);
mainView.appendChild(d1)
<div id="mainViewer"></div>
Thanks to #David Thomas for his comment :)

Change the onClick function to target the edit buttons

I have the following script
var counter = 0;
function appendText(){
var text = document.getElementById('usertext').value;
if ( document.getElementById('usertext').value ){
var div = document.createElement('div');
div.className = 'divex';
var li = document.createElement('li');
li.setAttribute('id', 'list');
div.appendChild(li);
var texty = document.createTextNode(text);
var bigdiv = document.getElementById('addedText');
var editbutton = document.createElement('BUTTON');
editbutton.setAttribute('id', 'button_click');
var buttontext = document.createTextNode('Edit');
editbutton.appendChild(buttontext);
bigdiv.appendChild(li).appendChild(texty);
bigdiv.appendChild(li).appendChild(editbutton);
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
document.getElementById('usertext').value = "";
counter++;
}
};
var makeAreaEditable = function(){
alert('Hello world!');
};
I want the makeAreaeditable function to work when the Edit button is pressed(for each of the edit buttons that are appended under the textarea).. In this state, the script, alerts me when i hit the Addtext button.
the following is the html. P.S. i need this in pure javascript, if you can help. thanks
<textarea id="usertext"></textarea>
<button onClick="appendText()">Add text </button>
<div id="addedText" style="float:left">
</div>
instead of:
document.getElementById('button_click').setAttribute('onClick', makeAreaEditable());
you need to do this:
editbutton.onclick = makeAreaEditable;
the function's name goes without brackets unless you want to execute it
instead of obtaining the element from the DOM using document.getElementById('button_click')
you can use the editbutton variable already created. this object is the DOM element you are looking for
SIDE NOTE:
the standard way to do it is to add the onclick property before appending the element

Add firstchild to newly added element

I need to create a new child to an existing element. The question add onclick event to newly added element in javascript helped me a lot.
I just can not define it as the first child. I can place it using position, but this is still insufficient. I searched on sites about JavaScript, but I found nothing.
Here is my code:
if( !document.getElementById('callbackButton')){
callback = function(){
var button = document.createElement('button');
button.id= 'callbackButton';
var textbutton =document.createTextNode("Liste des années d'étude");
button.appendChild(textbutton );
button.style.position='absolute';
button.style.top="60px";
button.style.left="45px";
button.style.width="200px";
button.style.height="18px";
button.onclick = function(){
getElementsByIdStarWith('etageres-virtuelle')[0].innerHTML = oldInnerHtml;
document.getElementById('etageres-virtuelles-etudes-germaniques').innerHTML = oldInnerHtml;
wrapPager();
};
document.getElementById('etageres-virtuelles-etudes-germaniques').appendChild(button);
};
This code works very well.
But this code doesn't work:
document.getElementById('etageres-virtuelles-etudes-germaniques').firstChild.nodeValue = button;
document.getElementById('etageres-virtuelles-etudes-germaniques').firstChild.nodeData = button;
This is not what I want. I want to display this new element on first place.
Any help would be appreciated. Thank.
Try this (untested):
var yourEl = document.getElementById('etageres-virtuelles-etudes-germaniques');
yourEl.insertBefore(button, yourEl.firstChild);

adding onclick event to dynamically added button?

I am adding a button dynamically in html like below:
On click of that button I want to call a Javascript function:
var but = document.createElement("button");
but.value="delete row";
but.setAttribute("onclick","callJavascriptFunction()");
//this is not working
but.onclick="callJavascriptFunction()"
//this is also not working
document.getElementById("but").onclick="callJavascriptFunction()"
//this is also not working
but.id="but"+inc;
How can this be resolved?
try this:
but.onclick = callJavascriptFunction;
or create the button by wrapping it with another element and use innerHTML:
var span = document.createElement('span');
span.innerHTML = '<button id="but' + inc +'" onclick="callJavascriptFunction()" />';
Remove the () from your expressions that are not working will get the desired results you need.
but.setAttribute("onclick",callJavascriptFunction);
but.onclick= callJavascriptFunction;
document.getElementById("but").onclick=callJavascriptFunction;
This code work good to me and look more simple. Necessary to call a function with specific parameter.
var btn = document.createElement("BUTTON"); //<button> element
var t = document.createTextNode("MyButton"); // Create a text node
btn.appendChild(t);
btn.onclick = function(){myFunction(myparameter)};
document.getElementById("myView").appendChild(btn);//to show on myView
Try
but.addEventListener('click', yourFunction)
Note the absence of parantheses () after the function name. This is because you are assigning the function, not calling it.
but.onclick = function() { yourjavascriptfunction();};
or
but.onclick = function() { functionwithparam(param);};
I was having a similar issue but none of these fixes worked. The problem was that my button was not yet on the page. The fix for this ended up being going from this:
//Bad code.
var btn = document.createElement('button');
btn.onClick = function() { console.log("hey"); }
to this:
//Working Code. I don't like it, but it works.
var btn = document.createElement('button');
var wrapper = document.createElement('div');
wrapper.appendChild(btn);
document.body.appendChild(wrapper);
var buttons = wrapper.getElementsByTagName("BUTTON");
buttons[0].onclick = function(){ console.log("hey"); }
I have no clue at all why this works. Adding the button to the page and referring to it any other way did not work.
Try this:
var inputTag = document.createElement("div");
inputTag.innerHTML = "<input type = 'button' value = 'oooh' onClick = 'your_function_name()'>";
document.body.appendChild(inputTag);
This creates a button inside a DIV which works perfectly!
but.onclick = callJavascriptFunction;
no double quotes no parentheses.
Using modern JavaScript, this solution works well:
let btn = document.getElementById("btnID");
btn.onclick = () => {onAction(url, method);};
for me this works!
button.onclick = () => (removechore());

Categories