setTimeout access element which is not available yet - javascript

I am trying to put together a hacky script to click some buttons on a website
I have a setTimeout function to click a button after sometime. After the button is clicked I have more DOM elements available which I have to click again. At no point does the whole page reload.
I tried the following
$("#id1").click();
setTimeout((){
var button2 = $("#id2");
button2.click();
}, 3000);
}, 3000)
id2 is not available initially and is available only after id1 is clicked. The above script therefore cannot click button 2, since it was not able to access it. How can I make my above condition work.

I have coded something like this.Create new button element manually and set a create function to onclick attribute. Hope it helps!
var counter = 1;
var ul = document.getElementById("list");
var btn1 = document.getElementById("id1");
// We've started to clicking 3 sec later!!
setTimeout(function(){
btn1.onclick = createNewButton;
btn1.click();
btn1.setAttribute("disabled",true);
},3000);
// This func create new button elements
// on each button click!!
function createNewButton(){
if(counter < 5) {
counter++;
var li = document.createElement("li");
var button = document.createElement("button");
button.setAttribute("id","id"+counter);
//button.onclick = createNewButton;
button.innerHTML = counter+".Button";
li.appendChild(button);
li.setAttribute("id","element"+counter);
ul.appendChild(li);
// Trigger next click event!!
setTimeout(function(){
button.onclick = createNewButton;
button.click();
button.setAttribute("disabled",true);
}, 3000);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
<ul id="list">
<li id="element1">
<button id="id1">1.Button</button>
</li>
</ul>
</div>

Related

Function inside of another function only works once

In my html page I have a button that creates another button when clicked. That created button creates a paragraph when clicked but this one only works once. It's two functions inside of each other which, I think, is the cause of the problem. What would be a better way of doing this?
Writing the inner function separate from the containing one gives me an error as the id the inner one tries to access doesn't exist until the containing one is called/the original button is clicked.
// Containing function
document.getElementById("buttonCreator").onclick=function() {
targetElement.innerHTML = (""); // Reset the main divs contents
var button1 = document.createElement("button"); // Create a button
var bContent = document.createTextNode("Click me!");
button1.appendChild(bContent);
button1.setAttribute("id", "createdButton"); // Give the button an id
targetElement.appendChild(button1);
// Inner function - this only works once
document.getElementById("createdButton").onclick=function() {
targetElement.innerHTML = targetElement.innerHTML
+ "<br> <br>"
+ ("You clicked the created button!);
}
}
There are no errors.
The problem is in targetElement.innerHTML = targetElement.innerHTML where you replace the original HTML which has the DOM event (click) attached with a new HTML and do not attach the event again.
You can try to create another function to handle this.
document.getElementById("buttonCreator").onclick=function() {
targetElement.innerHTML = (""); // Reset the main divs contents
var button1 = document.createElement("button"); // Create a button
var bContent = document.createTextNode("Click me!");
button1.appendChild(bContent);
button1.setAttribute("id", "createdButton"); // Give the button an id
targetElement.appendChild(button1);
button1.addEventListener('click', () => {
clickCreatedButton(targetElement, button1);
})
}
function clickCreatedButton(targetElement, button) {
button.addEventListener('click', () => {
targetElement.innerHTML = targetElement.innerHTML
+ "<br> <br>"
+ ("You clicked the created button!");
})
}

Javascript "Don´t change states to fast"

Hey guys i have an code which changes from one state to another when you click on a button(it starts a video and blends). Now i try to say my eventhandler if someone clicks very fast he shouldnt use it as input. Something like = Eventhandler please notice just oneclick in one sec. Hope this is understanble here my code :
<script>
var clickState = 0;
var btn = document.querySelector('#playbutton');
btn.addEventListener('click', function(){
if (clickState == 0) {
document.querySelector('#toggler').emit('fade_1');
var videoEl_1 = document.querySelector('#video');
videoEl_1.play();
document.querySelector( "#skyid" ).emit('fade_1');
clickState = 1;
} else {
document.querySelector('#toggler').emit('fade_2');
var videoEl_1 = document.querySelector('#video');
videoEl_1.pause();
document.querySelector( "#skyid" ).emit('fade_2');
clickState = 0;
}
});
</script>
You could disable the button when it is clicked and then set a timeout to reenable it after a second.
Like this
$( document ).ready(function() {
$("#myButton").click(function(){
// disable the button
$("#myButton").prop("disabled", true);
//do the things you want the button to do:
console.log("doing stuff");
// reenable the button after 1 second
setTimeout(function(){
$("#myButton").prop("disabled", false);
}, 1000);
});
});
Example here:
https://jsfiddle.net/20n1gb89/8/
I've used some jQuery here, but setTimeout is native JavaScript
edit:
It seems you are defining a click handler inside a click handler for the same button. See my comments. Remove the btn.addEventListener and just keep the if else statement. See if that works.
$(document).ready(function () {
// here you define a click handler for playbutton
$("#playbutton").click(function () {
// disable the button
$("#playbutton").prop("disabled", true);
//do the things you want the button to do:
var clickState = 0;
var btn = document.querySelector('#playbutton');
// here you define a click handler for the same button
// inside the first click handler. You shouldn't do that.
btn.addEventListener('click', function () {
if (clickState == 0) {
document.querySelector('#toggler').emit('fade_1');
var videoEl_1 = document.querySelector('#video');
videoEl_1.play();
document.querySelector("#skyid").emit('fade_1');
clickState = 1;
} else {
document.querySelector('#toggler').emit('fade_2');
var videoEl_1 = document.querySelector('#video');
videoEl_1.pause();
document.querySelector("#skyid").emit('fade_2');
clickState = 0;
}
console.log("doing stuff");
// reenable the button after 1 second
setTimeout(function () {
$("#playbutton").prop("disabled", false);
}, 2000);
});
});
});
edit 2:
That is. Try this:
$(document).ready(function () {
$("#playbutton").click(function () {
// disable the button
$("#playbutton").prop("disabled", true);
//do the things you want the button to do:
var clickState = 0;
// this doesn't really make sense. clickState will always be 0
// as it is defined as 0 each time you click the button. You
// will need to define clickState outside the click handler
// for this to work.
if (clickState == 0) {
document.querySelector('#toggler').emit('fade_1');
var videoEl_1 = document.querySelector('#video');
videoEl_1.play();
document.querySelector("#skyid").emit('fade_1');
clickState = 1;
} else {
document.querySelector('#toggler').emit('fade_2');
var videoEl_1 = document.querySelector('#video');
videoEl_1.pause();
document.querySelector("#skyid").emit('fade_2');
clickState = 0;
}
console.log("doing stuff");
// reenable the button after 1 second
setTimeout(function () {
$("#playbutton").prop("disabled", false);
}, 2000);
});
});
});
You can add an eventlistener on click and creating a timer with it
for example, here after the user clicks the button, we launch a 1000ms timer, if the button is clicked within this time-interval, we will display an alert.
var btn = document.querySelector('#playbutton');
btn.addEventListener('click', function(){
setTimeout(function(){
if (btn.clicked == true){
alert("Cmon dude, chill a little");
}
}, 1000);
});

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

Removing child by clicking a button

Having this JS code:
var prompter = (function(){
var prompt = document.createElement('div');
/* prompt-related stuff */
var closeBtn = document.createElement('button');
/* closeBtn stuff */
prompt.appendChild(closeBtn);
this.html = prompt;
this.show = (function(){
document.body.appendChild(this.html);
});
this.close = (function(){
document.body.removeChild(this.html);
});
});
If I do
var p = new prompter();
p.show();
It does show the prompter, and if I do p.close(); it disappears.
BUT what I want is that by clicking the closeBtn it indeed closes. I had the idea of adding an id to the prompt and then adding the attribute onclick to the button and performing the actions there via the id, but that looks really ugly...
You need to add an event listener to the button you made:
closeBtn.addEventListener("click", this.close.bind(this));

Categories