How to hide dynamically created div on ready? - javascript

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");

Related

TamperMonkey EventListener on button not working

I created this snippet:
function addClick(button, container) {
console.log("In add click");
const data = container.nextElementSibling.childNodes[0].innerHTML;
button.addEventListener('click', ()=>{
alert('clicked')
console.log("Clicked");
})
}
function createCopyButtons(array){
array.forEach(element => {
const container = document.createElement('div');
const button = document.createElement('button');
button.innerHTML = "Copy"
styleContainer(container);
styleButton(button, element);
stylePrevious(element);
container.innerHTML = element.outerHTML + button.outerHTML;
element.parentNode.replaceChild(container, element);
addClick(button, container);
});
}
Now in here the array is the array of DOM elements I want this property to apply and I call the createCopyButtons() function down with some more stuff. Now the thing is that this event listener does not apply or does not work. I tried to wait till the document is loaded by these answers and only then apply my javascript snippet but the event listener doesn't seems to work.
document.addEventListener("DOMContentLoaded", function(event) {
//do work
});
if (document.readyState == "complete") {
// document is ready. Do your stuff here
}
Please help.
update:
function addClick(button) {
button.addEventListener('click', ()=>{
console.log("Clicked");
})
}
let p = document.querySelectorAll('p');
// innerHTML not work
let btn1 = document.createElement('button');
btn1.innerHTML = "Not work";
p[0].innerHTML = btn1.outerHTML;
addClick(btn1)
// work
let btn2 = document.createElement('button');
btn2.innerHTML = "work";
p[1].appendChild(btn2);
addClick(btn2)
<p></p>
<p></p>
because you append the button to the container using string (.innerHTML) not DOM or using appendChild()
container.innerHTML = element.outerHTML + button.outerHTML
the following function will not apply the event
addClick(button, container);
I don't know why you need to wrap target element and the button inside div, why not just append the button after target element using or insertBefore() or insertAdjacentHTML() but below is working code that follow yours.
it find the button inside the container for using as addClick() parameters
function addClick(button, container) {
console.log("In add click");
const data = container.nextElementSibling.childNodes[0].innerHTML;
button.addEventListener('click', () => {
alert('clicked')
console.log("Clicked");
})
}
function createCopyButtons(array) {
array.forEach(element => {
const container = document.createElement('div');
let button = document.createElement('button');
button.innerHTML = "Copy"
container.innerHTML = element.outerHTML + button.outerHTML;
element.parentNode.replaceChild(container, element);
let btn = container.querySelector('button'); // <== find the button
addClick(btn, btn.parentNode);
});
}
createCopyButtons(document.querySelectorAll('input'))
<div>
<input type="text">
<p><span>test</span></p>
</div>

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>

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);

adding click event in newly created div in 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");
}

Categories