How to stop a Javascript alert from reappearing in an infinite loop - javascript

The alert dialog created in the onclick reappears every single time I dismiss it in an infinite loop. This occurs in both Chrome and Firefox. This is my first day learning Javascript so please be gentle.
Is there a way to make the alert dialog appear only once?
This might be a problem with my computer. If so, what do I do to fix that?
<!DOCTYPE html>
<html>
<body>
<h1>What Can JavaScript Do?</h1>
<p id="demo">JavaScript can change the style of an HTML element.</p>
<p>"The text should turn red and one alert dialog should appear on click."</p>
<script>
function changeFontRed() {
var x = document.getElementById("demo");
x.style.color = "red";
console.log("Hello World!");
window.alert("Hello World!");
x.removeEventListener("onclick", changeFontRed(), false);
x.addEventListener("onclick", changeFontBlue());
}
function changeFontBlue() {
var x = document.getElementById("demo");
x.style.color = "blue";
x.removeEventListener("onclick", changeFontBlue(), false);
x.addEventListener("onclick", changeFontRed());
}
</script>
<button type="button" onclick="changeFontRed()">Click Me!</button>
</body>
</html>
Thanks guys.

These lines:
x.removeEventListener("onclick", changeFontRed(), false);
x.addEventListener("onclick", changeFontBlue());
You are calling the functions changeFontRed and changeFontBlue, not just naming them. The parenthesis () mark an invocation, and when the function is called again the dialog reappears.
Also (thanks to commenters) the event is named "click". Try this:
x.removeEventListener("click", changeFontRed, false);
x.addEventListener("click", changeFontBlue);

There are some problems with your code, but the infinite loop problem is in the line below:
x.removeEventListener("onclick", changeFontRed(), false);
More specifically, that part: changeFontRed(). Although you're trying to remove the changeFontRed event listener off your element, what you're really doing is calling that function and passing the return value to the removeEventListener function. And as soon as you're already inside the changeFontRead function, it will be calling itself recursivelly, until it turns into a stack overflow.
The removeEventListener function expects as the second paramenter a function reference, that will be called only when the button is clicked. So, to fix your problem, you must remove the (), and pass the function itself. E.g: removeEventListener('click', changeFontRed).
But there are other problems in your code, for example the "onclick" you're passing as the first parameter, because the addEventListener method won't understand it, since you shouldn't pass "on[event name]", but only "[event name]". So, it should be "click" only.

the second argument for remove/addEventListener should be a function, not the result of calling the function (as answered already).
first argument for remove/addEventListener should be 'click' not 'onclick'.
The button click will work the first time only, after that, you click the text that changes colour to change the colour again.

The second argument to removeEventListener and addEventListener should be a function. You're not passing the function, you're calling the function because you have () after it. Take that out.
function changeFontBlue() {
var x = document.getElementById("demo");
x.style.color = "blue";
x.removeEventListener("click", changeFontBlue, false);
x.addEventListener("click", changeFontRed);
}
Also, the name of the event is just click, not onclick.

Related

Why is my Auto-Clicker script getting this Uncaught TypeError?

So, I'm new to JavaScript and I am trying to make an auto-clicker script. The problem is when I execute the script in the Developer Console, I get an error called "button.click is not a function" and the error just loops forever and the console. Here is my code:
var button = document.getElementsByClassName("btn btn-default");
setInterval(function(){
button.click()
},200)
How do I fix this?
document.getElementsByClassName returns an array check this example:
<button class="btn-default" onclick="console.log('clicked');"></button>
<script>
var button = document.getElementsByClassName("btn-default")[0];
setInterval(function(){
button.click()
},1000)
</script>
Due to specification, getElementsByClassName returns an array-like object of all child elements which have all of the given class names. So your "button" could not have click property, it's an array. You need to take an element, for example the first element:
var button = document.getElementsByClassName("btn btn-default")[0];
But I would say that if you have a button click handler logic and you want to run it by some timer, then the best way would be to extract that logic into a function (let's name it onClick) and run this function by timer instead of click event emulation:
var onClick = function () {
console.log("click!");
// your click hanlder logic
};
setInterval(onClick, 200);
button.addEventListener("click", onClick);
This also means that you don't bind the handler with onclick attr (<button onclick="onClick()">), but with addEventListener, and this is preferable way to provide events handling.

change attributes on button

I'm attempting to do a project in which I need to change attributes on a button. I have no code for you, but I still need help. Is there any way I can change a button that's already there so that the onclick attribute runs a different function from before? Thanks in advance.
I feel like all the answers so far miss the main point. Since you don't have any code examples, I'm guessing you'll find it hard to extrapolate out what everyone is saying.
So, one button, which when clicked, changes to another method, and when clicked again, changes back. I'm using the onclick attribute for simplicity, but as others have shown, using JavaScript .onclick or addEventListener is a better choice.
function function1(e) {
// Show where we're at
alert("function1 is running");
// Get which button was clicked from the event that is passed in, and set its onclick event
e.currentTarget.setAttribute("onclick", "function2(event)");
}
function function2(e) {
// Show where we're at
alert("function2 is running");
// Get which button was clicked from the event that is passed in, and set its onclick event
e.currentTarget.setAttribute("onclick", "function1(event)");
}
<button onclick="function1(event)">Click Me!</button>
You can of course change what function1 and function2 do, and add more changes (e.g. function 3 and 4), add logic for when to change, and so on.
use .onclick = function_name;
Demo :
document.getElementById('myButton').onclick = fun2;
function fun1() {
alert('I am from Function 1');
}
function fun2() {
alert('I am from Function 2');
}
<button id='myButton' onclick='fun1()'>Click me</button>
Yes, you can. There's only one thing to keep in mind:
An event on which you want the change to happen
Once you have identified that event, just bind it with JQuery's .attr() function to change any attribute.
Read more: http://api.jquery.com/attr/
Javascript Events: https://developer.mozilla.org/en-US/docs/Web/API/Event
Use jQuery like:
$("mybtn").click(function(){
$("#mybtn").attr({
"onclick" : "anotherFunction()",
});
});
Yes, it's possible. Check this fiddle: https://jsfiddle.net/gerardofurtado/ga3k7ssp/1/
I set a variable to 0 and this function for button 1:
bt1.onclick = function(){
i++;
myPar.innerHTML = i;
};
It increases the variable and displays the number.
But, clicking on button 2, it changes button 1 function:
bt1.onclick = function(){
i--;
myPar.innerHTML = i;
};
Now button 1 decreases the variable.
This other fiddle is similar, but using radio buttons, to show that you can set the original function of button 1 back: https://jsfiddle.net/gerardofurtado/8gbLq355/1/

referencing a dynamically created element in html

I have an input field(search_text), which shows the images (id="demo2") from a database when the user puts in more than 1 letter.
And then I have a draw function (draw()) that is supposed to do something when the image is being clicked, (after it got displayed from the database).
The problem is the image (id="demo2") does not exist in the Html DOM, only after the user has put in more than 1 letter.
Now, I have:
function myFunction(){
console.log('success');
alert("I am an alert box!");
console.log('success2');
var x = document.getElementById("demo2");
console.log(x);
x.addEventListener("click", myFunct);
console.log(x);
}
function myFunct(){
currentImg=document.getElementById("demo2");
draw();
}
function myFunction2(){
//alert("I am an alert box!");
var x = document.getElementById("search_text").value;
if (x.length >2){myFunction();}
}
which works when I slowley type in the searchterm and the alertbox comes and after that, when I click the image, the draw() function works.
When I take out the alert it won't work. Somehow the alert lets the user wait until the image is loaded/created. How do I achieve this without the alert?
Thanks!
You can use the jQuery function $.on() to bind an action to a not yet created element. You just specify it to be on an alement that exists when the code is running, such as the body element.
See the fiddle below. The HEY button wont appear until after 3 seconds, but since we bind the click event to it as described above, we wont have any problem.
//This is how you bind to a dynamically created element
$('body').on('click', '.myclass', myFunction);
setTimeout(function() {
var button = document.createElement('button');
button.className = "myclass";
button.appendChild(document.createTextNode("HEY"));
$('#button-cell').append(button);
}, 3000);
function myFunction() {
alert("It's working!");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td id="button-cell"></td>
</tr>
</table>
Even though this works, I'd suggest you might look into adding your elements directly and then toggling their visibility.
use setTimeout to make it run in a separate thread which would be what alert does otherwise:
function myFunction2(){
setTimeout(function(){
var x = document.getElementById("search_text").value;
if (x.length >2){
myFunction();
}
},100)//keep minimal time.
}
Suggestion:
Why don't you add element to DOM toggle the display of an element instead of creating it after typing 2 chars?

purpose of the "function()" for attaching a function to a eventlistener

Sorry if the question looks stupid, but I have been confused for long time.
I want to alert "viola" when the button is clicked.
The second example below doesn't work as expected because I didn't include "function()"
Intuitively I think the second example should be working since I have attached a function(allert) to the element(button) and eventlistener(onclick).
Therefore I really wondered the purpose of including function(). Thanks.
Example 1
<html>
<button id="clickme">Hello,I'm a button,click me</button>
<script>
var button=document.getElementById("clickme");
clickme.onclick=function() {alert("viola");}
</script>
</html>
Example 2
<html>
<button id="clickme">Hello,I'm a button,click me</button>
<script>
var button=document.getElementById("clickme");
clickme.onclick=alert("viola");
</script>
</html>
clickme.onclick=alert("viola");
doesn't register the function alert(..), but the result of calling that function.
The onclick field expects a function, to be executed later, when the button is clicked. You don't want to execute that function when you're installing the handler.
You could also write:
clickme.onclick=myfunction;
function myfunction() { alert("viola") }
An event listener can only be a function.
alert("viola")
is not a function but actually undefined. That’s because
clickme.onclick=alert("viola");
means “assign the return value of alert(…) to clickme.onclick”. alert("viola") is being called immediately and the result of calling it is assigned.
The wrapper function(){…} actually assigns the function with the alert that is then called later.

Not work my function after click?

I not know why not work following code for my function(alert()) and is run my function(alert()) after tow times click on button, did you can guide me?
Demo:(Here see my full code) http://jsfiddle.net/pRXQ7/1/
$('.iu').click(function() {
if(alert() == true){
alert('ok')
}else{
alert('no')
}
});
By naming your function alert, you've effectively overridden the native javascript alert function. Name it something else.
Also, in your alert function, you are referencing this. In the scope of the function, this points to the document object, not the element which was clicked. Try passing the element instance to your function from the click event handler.
See http://jsfiddle.net/pRXQ7/15/

Categories

Resources