First I displayed the div on screen and now I want to use the the button to create that same div(or any other action) after user input.
document.getElementById("add").addEventListener("click", function() {
document.getElementById("welcome").style.display = "block";
}
How do i make the button be able to work again after the first thing it did?
It isn't customary to reuse a UI element in different ways as it tends to confuse the end user. But if you must...
document.getElementById("add").addEventListener("click", showWelcome);
function showWelcome() {
document.getElementById("welcome").style.display = "block";
document.getElementById("add").removeEventListener("click", showWelcome);
reassignButton();
}
function resassignButton(){
// some decision logic for next button function
document.getElementById("add").addEventListener("click", doNextThing);
}
function doNextThing(){
// removes eventlistener on add button. does whatever
}
You can use removeEventListener to remove the handler and then set a new one.
var ele = document.getElementById('btn');
ele.addEventListener("click", function click1(){
//Do stuff for the first click
this.innerHTML = "Click Me Again";
alert("Hello");
//Remove the event hendler
this.removeEventListener("click", click1, true);
//Attach handler for rest of clicks
ele.addEventListener("click", function click2(){
alert("You cicked again!");
}, true);
}, true);
<button id=btn>Click Me</button>
Although it's probably more practical to re-use a single event listener, as assigning and re-assigning event listeners can sometimes lead to memory leaks..
(()=>{
var ele = document.getElementById('btn');
var clicks = 0;
ele.addEventListener("click", function(){
if(clicks){
alert("Thanks for clicking again");
}else{
alert("Hello");
this.innerHTML = "Click again";
}
clicks++;
}, true);
})();
<button id=btn>Click Me</button>
You can make several methods and use these with the onclick attribute of button.
Also I advise you to use jQuery. It's easy and faster than JS.
Related
document.getElementById("btn2").onclick = false;
I did this to stop getting on click event after the first one and when I want to set it back to normal
document.getElementById("btn2").onclick = True;
it does not take click events
You could always disable the button, like this:
document.getElementById("btn2").disabled = true;
This sets the disabled attribute to true, therefore stopping the onClick function from being called when the user clicks the button.
Declare a variable boolean and change using logical not operator (!: see in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_NOT), example:
let toggle = true;
let button = document.querySelector('button');
let result = document.querySelector('span');
button.onclick = () => {
toggle = !toggle;
result.textContent = `Your switch to ${toggle}`;
}
<button>Click me</button>
<span></span>
You may not set onclick event as True instead try this way.
const setEvent = (enable) => {
if(enable){
document.getElementById("btn2").addEventListener('click', onClickEvent);
}
else{
document.getElementById("btn2").removeEventListener('click');
}
}
function onClickEvent(){
//Your actual event when clicking the button
}
//Now enable or disable the event as follows
setEvent(true); //Will attach the event
setEvent(false); //Will remove the event
Make sure you call setEvent(true) once only, because it can attach multiple events.
I have a button:
<script>
function never(){
alert('This is place holding text');
}
</script>
<button onclick="never()">Understood</button>
I need to use local storage or cookies to remember if the button has ever been clicked, and if it has, to run the function and if it hasn't to not run the function until they click the button, I've had an idea...
Onload Run Function.
Check if button has been clicked, then run function.
Else do not run function.
If button is clicked set cookie or value to run function automatically now.
I have no idea how to actually implement this though, or if this won't work. And yes, I know the real solution would be server side, but I do not have a server.
You can check this implementation
You can just store some value to localStorage when clicked and then read those values later.
HTML
<button id="btn">Click Me</button>
JavaScript
const btn = document.querySelector("#btn");
if(localStorage.getItem('clicked')) btn.innerText = 'clicked once';
btn.addEventListener('click', handleClick);
function handleClick(event) {
if(localStorage.getItem('clicked')) return;
else {
localStorage.setItem('clicked', true);
btn.innerText = 'clicked once';
}
}
do u mean this way :
<button onclick="run()">Click</button>
function run(){
localStorage.setItem('item','value');
}
or something else ??
or try this way
var someData = 'any data.';
localStorage.setItem('myData', '')
function never(){
localStorage.setItem('myData', someData);
alert('This is place holding text');
}
var data = localStorage.getItem('myData');
if (data != ""){
never()
}
localStorage.removeItem('myData')
<button onclick="never()">Understood</button>
I am trying to make a simple Shopping List App in which user can Add, Delete and mark the task done when completed. So far, I am able to add the task but facing problem in executing the done and delete functions. I am getting an error because when I execute it, the done and delete buttons are not there but what should I do to fix it?
var inp = document.getElementById("form");
var button = document.getElementById("click");
//Create List Function with Done and Delete Buttons
function addVal() {
var ul = document.getElementById("list");
var li = document.createElement("li");
var span = document.createElement("span");
var done = document.createElement("button");
var del = document.createElement("button");
li.appendChild(document.createTextNode(""));
span.appendChild(document.createTextNode(inp.value));
done.appendChild(document.createTextNode("Done"));
del.appendChild(document.createTextNode("Delete"));
li.appendChild(span);
li.appendChild(done);
li.appendChild(del);
done.setAttribute("class", "doneBut");
del.setAttribute("class", "delBut");
ul.appendChild(li);
inp.value = "";
}
//Get Input Length
function checkLength() {
return inp.value.length;
}
//Run function on Button Click
function onButtonClick() {
if (checkLength() > 0) {
addVal();
}
}
//Run function on Enter Keypress
function onEnter(event) {
if (checkLength() > 0 && event.which === 13) {
addVal();
}
}
//Trigger Events
button.addEventListener("click", onButtonClick);
inp.addEventListener("keypress", onEnter);
//Done and Delete Button Functions
var doneButton = document.getElementsByClassName("doneBut");
var deleteButton = document.getElementsByClassName("delBut");
function doneTask() {
doneButton.parentNode.classList.add("done");
}
function delTask() {
deleteButton.parentNode.classList.add("delete");
}
doneButton.addEventListener("click", doneTask);
deleteButton.addEventListener("click", delTask);
<input type="text" placeholder="Enter Your Task..." id="form" />
<button id="click">Add Task</button>
<h2>List:</h2>
<ul id="list"></ul>
Please Help.
Your problem is that the code tries to add events before the buttons exist. The buttons don’t exist until the addVal function gets called. Since addVal is not being called before the you try to add your event handlers, the getElementById returns null, and you attempt to add an event listener to null.
Additionally it looks like you’re planning to add multiple done and delete buttons. That wouldn’t normally be a problem, except you’re referencing them by ID, and IDs MUST be unique. You’ll need to switch this to a class or an attribute, since you’ll need one per item in the shopping cart.
You’ll probably want to look into event delegation, so that you can add your events once to the page before any buttons exist. https://javascript.info/event-delegation
It's most likely because your script is running before your code is running. Add the <script> tags just before the closing </body> tag to fix it:
<script>/* Your code here */</script>
</body>
You need to place this in a window.onload function, or run it in a function inside of the body tag's onload. Those elements don't exist yet when the script is run:
window.onload = function() {
var inp = document.getElementById("form");
var button = document.getElementById("click");
button.addEventListener("click", onButtonClick);
inp.addEventListener("keypress", onEnter);
}
I am trying to add a click function that triggers when a button is clicked. I am also trying to figure out how to add a double click function onto the same element, that triggers a different event.
var click = false;
onEvent("image2", "click", function(event) {
click = true;
});
if (click === true) {
setTimeout(function() {
onEvent("image2", "click", function(event) {
setScreen("safeScreen");
console.log("double click");
});
}, 200);
} else {
onEvent("image2", "dblclick", function(event) {
setScreen("safeScreen");
console.log("click");
});
}
This code is completely wrong, but I don't know where to start/correct. What am I doing wrong? I am looking to have the single click not trigger when the user double clicks.
Update:
Try passing a function clicks() to your event listener like so:
onEvent("image2", "click", clicks);
Function clicks() will check if there was a single or double click based on setTimeout function. You can adjust setTimeout via timeout variable and of course you need clickCount variable declared outside clicks() function.
Pure js approach
Try adding two event listeners. Less code, much cleaner. Check this working example.
var selector = document.getElementById('codeorg');
selector.addEventListener('click', clicks);
// Global Scope variable we need this
var clickCount = 0;
// Our Timeout, modify it if you need
var timeout = 500;
// Copy this function and it should work
function clicks() {
// We modify clickCount variable here to check how many clicks there was
clickCount++;
if (clickCount == 1) {
setTimeout(function(){
if(clickCount == 1) {
console.log('singleClick');
// Single click code, or invoke a function
} else {
console.log('double click');
// Double click code, or invoke a function
}
clickCount = 0;
}, timeout || 300);
}
}
// Not important for your needs - pure JS stuff
var button = document.getElementById('button');
button.addEventListener('click', singleClick);
button.addEventListener('dblclick', doubleClick);
function singleClick() {
//console.log('single click');
}
function doubleClick() {
console.log('double click');
}
#codeorg {
margin-bottom: 100px;
}
<h2>Double Click</h2>
<button id="button">Click me</button>
<hr><hr>
<h2>Double click or Single Click</h2>
<button id="codeorg">Click me</button>
I have created a javascript function to dynamically create a button
function btn(d) {
var btn = document.createElement("BUTTON");
var t = document.createTextNode(d);
btn.appendChild(t);
btn.className = "myButton";
btn.onclick = alert('hello');
document.body.appendChild(btn);
}
when this function is called, alert is poping up even if button is not clicked. I want the alert when button is clicked. May be i am missing something. Please help. Thanks
you are calling the alert function not assigning a function
alert('hello'); // evals immediately.
btn.onclick = function () {
alert("Hello World"); // gives the button a click handler
// which can be called when clicked
};
Try doing it with jQuery, like so (per your jQuery tag on the question):
function btn(d) {
var btn = $('<button/>').addClass('myButton').text(d).appendTo('body').click(function (e) {
alert('hello');
})
}
onclick should look like:
btn.onclick = function(){alert('hi');};
You are assigning the return value of alert('hello'); to the onclick, while it is expecting a function. The correct way without jQuery would be
if (btn.addEventListener)
btn.addEventListener ('click',function(){ alert('hello');}, false);
else if (btn.attachEvent)
btn.attachEvent ('onclick',function(){ alert('hello');});