adding click event in newly created div in javascript - javascript

I am creating a new div on a click of button and inside that onclick function I am adding a click event to newly created div but its not working.
document.getElementById('blah').onclick = function(){
var innerDiv = document.createElement("div");
document.getElementById('container').appendChild(innerDiv);
innerDiv.onclick =createWorkFunction;
}
function createWorkFunction(e){
alert();
}
can anybody quickly help me

Your code is corrct, But you did not set the text of the your div (an empty div can not be clicked by an user), Try this:
document.getElementById('blah').onclick = function(){
var innerDiv = document.createElement("div");
innerDiv.innerHTML = 'This is a div'; // set it's text
document.getElementById('container').appendChild(innerDiv);
innerDiv.onclick = createWorkFunction;
}
function createWorkFunction(e){
alert('this is some text');
}
Also it's better to use addEventListener

(function() {
var oBlah = document.getElementById('blah');
oBlah.addEventListener('click', function() {
var innerDiv = document.createElement("div");
document.getElementById('container').appendChild(innerDiv);
}, false);
innerDiv.addEventListener('click', function() {
alert();
}, false);
})();
This should help.

try this:
innerDiv.setAttribute("onclick","createWorkFunction()")
function createWorkFunction(){
alert("working");
}

Related

how to make multiple click events on the same element?

How can I use several click events on the same element in JavaScript?
I try to make that when I click on the h3 element it opens its description and then I again click on the element it closes the description.
var p, img, question;
function clickOn(){
img = document.getElementsByClassName('down-arrow')[0];
p = document.querySelectorAll('p')[0];
p.setAttribute('class','show-text');
/*img.setAttribute('class','show');*/
}
function clickOff(){
img = document.getElementsByClassName('down-arrow')[0];
p = document.querySelectorAll('p')[0];
p.removeAttribute('class','show-text');
/*img.removeAttribute('class','show');*/
}
question = document.getElementsByClassName('question')[0];
question.addEventListener('click', clickOn, false);
question.addEventListener('click', clickOff, false);
Try using toggle for adding and removing class https://www.w3schools.com/howto/howto_js_toggle_class.asp:
var p, img, question;
function clickOn(){
img = document.getElementsByClassName('down-arrow')[0];
p = document.querySelectorAll('p')[0];
p.classList.toggle('show-text');
}
question = document.getElementsByClassName('question')[0];
question.addEventListener('click', clickOn, false);
You can declare a global variable
var isTextDisplayed = false;
Then you can call same event listener and open or close the description on basis of the bit. For example
document.getElementById("myBtn").addEventListener("click", function() {
if(!isTextDisplayed) {
//HIDE DESCRIPTION CODE
}
else {
//SHOW DESCRIPTION CODE
}
isTextDisplayed = !isTextDisplayed;
});
Full code:
var isTextDisplayed = false;
var description = document.getElementById("description");
document.getElementById("myBtn").addEventListener("click", function() {
if(!isTextDisplayed) {
description.style.display = 'none';
}
else {
description.style.display = 'block';
}
isTextDisplayed = !isTextDisplayed;
});
<h3 id="myBtn">CLICK TO TOGGLE DESCRIPTION</h3>
<p id="description">
Some dummy text for description goes here in the block
</p>
For demo, see JSFIDDLE CODE

How do I add a button to a div class on load from Javascript? [duplicate]

This question already has answers here:
How to add onload event to a div element
(26 answers)
Closed 5 years ago.
For an assignment, I cannot touch the HTML code and am editing an external JS file. I have to refer the code to an existing class and turn that into a button to run a script.
The has to be ran on load to transform an element with a given id into a button that can also run a function on click.
So let's say the we have id="bar",
how do I go about it?
My code doesn't work at all.
document.getElementById("bar").onload = function () { myFunction() };
function myFunction() {
document.getElementById("bar").innerHTML = "<button></button>";
}
Why don't you just execute your script as the DOM is ready? To do so,
document.addEventListener('DOMContentLoaded', function () {
document.getElementById("bar").innerHTML = "<button></button>";
}, false);
You just need a createElement function.
This works:
document.addEventListener("DOMContentLoaded", function(){
var button = document.createElement("button");
button.innerHTML = "This is a button";
// assuming the Div's ID is bar
var div = document.getElementById('bar');
div.appendChild(button);
//the following function will alert a window when the button is clicked
button.addEventListener ("click", function() {
alert("Button was clicked");
});
});
Updated Codepen
I think this is bit tha you needed
var bar = document.getElementById('bar');
window.onload = function() {
var barInner = bar.innerHTML;
bar.innerHTML = '<button>' + barInner + '</button>';
}
bar.onclick = function() {
alert("Hello\nHow are you?");
};
document.getElementById("bar").onload = myFunction();
function myFunction() {
document.getElementById("bar").innerHTML = "<button>Button</button>";
}
There you go!
Not every single HTML element has a load event.
Only some of them are concerned, such as the window, an image... etc
Have a look here on MDN to learn more about this.
Here is a simple snippet resolving all what you mentioned.
window.addEventListener("load", () => {
// you can put your entire script in here.
var elt = document.getElementById("bar"),
button = document.createElement("button");
button.textContent = elt.textContent;
button.onclick = callback;
elt.textContent = '';
elt.appendChild(button);
function callback() {
console.log("The button has been clicked");
}
});
<div id="bar" style="background: beige; height: 2em">Click me</div>
In the previous snippet, I am appending the button in the element. But if the matter is really to transform it into a button, there we go:
window.addEventListener("load", () => {
// you can put your entire script in here.
var elt = document.getElementById("bar"),
container = elt.parentNode,
button = document.createElement("button");
button.id = elt.id; // if you want to keep the id
button.textContent = elt.textContent;
button.onclick = callback;
container.removeChild(elt);
container.appendChild(button);
function callback() {
console.log("The button has been clicked");
}
});
<div style="background: #fee; height: 2em">
<div id="bar" style="background: beige; height: 2em">Click me</div>
</div>

How to hide dynamically created div on ready?

I have a scenario where I need to create a div dynamically, so I created on-ready of document. But it should be displayed on-selection. I am facing the issue, that on page load, the empty div is created. So I need to hide that div and should be shown on-select of text.
JavaScript
$(document).ready(function () {
closePopUp();
var replaceDiv = document.createElement('div');
replaceDiv.id = 'rplceTxtDiv';
document.getElementsByTagName('body')[0].appendChild(replaceDiv);
var innerspan = document.createElement('span');
replaceDiv.appendChild(innerspan);
innerspan.innerHTML += '˟';
var innerDiv = document.createElement('div');
replaceDiv.appendChild(innerDiv);
innerspan.addEventListener("click", closePopUp, false);
replaceDiv.addEventListener("click", getSel, false);
var rplceTxtDiv = $('#rplceTxtDiv');
$('#mytextarea').on('select', function (e) {
var txtarea = document.getElementById("mytextarea");
var start = txtarea.selectionStart;
var finish = txtarea.selectionEnd;
rplceTxtDiv.offset(getCursorXY(txtarea, start, 20)).show();
rplceTxtDiv.find('div').text('replace with stars');
}).on('input', function () {
if (interval) {
interval = false;
edits.push($(this).val());
if (edits.length > maxHistorySize) edits.shift();
setTimeout(() => interval = true, saveInterval);
}
});
document.onkeydown = undo;
});
Here is my plunker
The issue is shown in below image:
Hide the DIV before appending it to the HTML by
replaceDiv.style.display = "none";
and I recommend showing it after you have updated the text by
replaceDiv.style.display = "block";
Set a CSS class as:
.MyClass {
display: none;
}
and with jQuery:
$('#myDivIDorClass').addClass('MyClass');
just hide all div having class name "yourclass" with hide()
like this on ready
$('div.yourclass').css("display","none");

Get image ids in a div every second

I was successful in getting the id of all images within a div when clicking the div with the following codes below:
<script type="text/javascript">
function getimgid(){
var elems = [].slice.call( document.getElementById("card") );
elems.forEach( function( elem ){
elem.onclick = function(){
var arr = [], imgs = [].slice.call( elem.getElementsByTagName("img") );
if(imgs.length){
imgs.forEach( function( img ){
var attrID = img.id;
arr.push(attrID);
alert(arr);
});
} else {
alert("No images found.");
}
};
});
}
</script>
The codes above works perfectly, doing an alert message of the image id when clicking card div. Now what I want is to run this function without clicking the div in every 5 seconds. I have tried setInterval (getimgid, 5000), but it doesn't work. Which part of the codes above should I modify to call the function without clicking the div. Any help would be much appreciated.
JSFiddle
You should be calling it this way:
setInterval (function(){
getimgid();
},5000);
also remove binding of click event for element.
Working Fiddle
Use elem.click() to trigger click
function getimgid() {
var elems = [].slice.call(document.getElementsByClassName("card"));
elems.forEach(function (elem) {
elem.onclick = function () {
var arr = [],
imgs = [].slice.call(elem.getElementsByTagName("img"));
if (imgs.length) {
imgs.forEach(function (img) {
var attrID = img.id;
arr.push(attrID);
alert(arr);
});
} else {
alert("No images found.");
}
};
elem.click();
});
}
setInterval(getimgid, 1000);
DEMO
Problem: You are not triggering the click in setInterval. You are only re-running the event binding every 5 secs.
Solution: Set Interval on another function which triggers the click. Or remove the click binding altogether if you don't want to manually click at all.
Updated fiddle: http://jsfiddle.net/abhitalks/3Dx4w/5/
JS:
var t;
function trigger() {
var elems = [].slice.call(document.getElementsByClassName("card"));
elems.forEach(function (elem) {
elem.onclick();
});
}
t = setInterval(trigger, 5000);

Removing event listeners on automatically created multiple elements

I'm trying to remove event listeners from elements after they've been clicked on and although I seem to have a working solution, it's not ideal and I'm not sure why it works differently to the broken code.
Although I realise there are simpler ways of doing this, this is taken from a JS class I'm working on so need to retain some of the structure.
This relates to a previous post I made which was answered correctly (but didn't work when I expanded the example) - Removing event listeners with anonymous function calls in JavaScript.
In this example, the last created div removes the listener correctly but earlier ones don't (fiddle here - http://jsfiddle.net/richwilliamsuk/NEmbd/):
var ctnr = document.getElementById('ctnr');
var listener = null;
function removeDiv (d) {
alert('testing');
d.removeEventListener('click', listener, false);
}
function addDiv () {
var div = document.createElement('div');
div.innerHTML = 'test';
ctnr.appendChild(div);
div.addEventListener('click', (function (d) { return listener = function () { removeDiv(d); } })(div), false);
}
addDiv();
addDiv();
addDiv();
In the version I got working I create an array which holds all the listeners (fiddle here - http://jsfiddle.net/richwilliamsuk/3zZRj/):
var ctnr = document.getElementById('ctnr');
var listeners = [];
function removeDiv(d) {
alert('testing');
d.removeEventListener('click', listeners[d.id], false);
}
function addDiv() {
var div = document.createElement('div');
div.innerHTML = 'test';
ctnr.appendChild(div);
div.id = listeners.length;
div.addEventListener('click', (function(d) {
return listeners[listeners.length] = function() {
removeDiv(d);
}
})(div), false);
}
addDiv();
addDiv();
addDiv();
document.getElementById('btn').addEventListener('click', function() {
alert(listeners);
}, false);​
The final one works fine but I'm sure the listener array shouldn't be necessary. Maybe I'm worrying too much but I'd like to know the optimal solution.
you are right, you don't need an array, just hold every listener in a variable, than pass eventlistener in your remove() function,
var ctnr = document.getElementById('ctnr');
function removeDiv(d, ev) {
alert('testing');
d.removeEventListener('click', ev, false);
}
function addDiv() {
var div = document.createElement('div');
div.innerHTML = 'test';
ctnr.appendChild(div);
div.addEventListener('click', (function(d) {
var myfunc;
return myfunc = function() {
removeDiv(d, myfunc);
}
})(div), false);
}
addDiv();
addDiv();
addDiv();
document.getElementById('btn').addEventListener('click', function() {
alert(listeners);
}, false);​​
updated jsfiddle page
You have to save each and every listener if they are unequal, so you need a relation between listener and element. Since an element is represented by an object (DOM: document object model) you can add custom properties to them (although it's not recommended: Can I add arbitrary properties to DOM objects?) (demo):
var ctnr = document.getElementById('ctnr');
function removeDiv (d) {
alert('testing');
d.removeEventListener('click', d.custom_Listener , false);
}
function addDiv () {
var div = document.createElement('div');
div.innerHTML = 'test';
div.custom_Listener = function(){removeDiv(this)};
ctnr.appendChild(div);
div.addEventListener('click', div.custom_Listener , false);
}
But since your using the same listener in every div its even better not to use a separate function for every div but the same (demo):
var ctnr = document.getElementById('ctnr');
var listener = function(){
removeDiv(this);
};
function removeDiv (d) {
alert('testing');
d.style.backgroundColor = '#36f';
d.removeEventListener('click', listener, false);
}
function addDiv () {
var div = document.createElement('div');
div.innerHTML = 'test';
ctnr.appendChild(div);
div.addEventListener('click', listener , false);
}

Categories