I am a beginner in javascript, can you tell me what's wrong with the below code?
I want this to invoke buttonPressed() when a button gets pressed. From buttonPressed() it should call changeColor1(), changeColor1() should change the text color of a paragraph, and start a timer to invoke changeColor2(). Similarly changeColor2() should also change the color and call changeColor1() once the timer expires.
<html>
<head>
<script type="text/javascript">
function changeColor2()
{
alert("2");
var v = document.getElementById("onet");
v.style.color = rgb(0,255,255); // this statement is not working
var t=setTimeout(changeColor1,3000);
}
function changeColor1()
{
alert("1");
var v = document.getElementById("onet");
v.style.color = rgb(255,255,0); // this statement is not working
var t=setTimeout(changeColor2,3000);
}
function buttonPressed()
{
alert("Hello");
changeColor1();
}
</script>
</head>
<body>
<p id="onet"> Hello how are you? </p>
<form>
<input type="button" value="Display alert box!" onClick="buttonPressed()" />
</form>
</body>
</html>
Do not invoke the function, pass the reference only:
var t=setTimeout(changeColor2,3000);
I think you want style.color not .color.
By the way... please tell us what the code is supposed to actually do and what is wrong initially.
You need to quote style property values-
v.style.color = 'rgb(255,255,0)';
1) I don't like the fact that you have two timeouts set. Just call one function and use a flag to toggle between the two options.
2) The parameter to setTimeout that you want to use is a function pointer (changeColor) not the result of a function call (changeColor())
var flag = false;
var t;
function changeColor()
{
var v = document.getElementById("onet");
if(flag){
v.color = rgb(255,255,0);
} else {
v.color = rgb(0,255,255);
}
flag = !flag;
}
function buttonPressed()
{
alert("Hello");
t=setInterval(changeColor,3000);
}
Not really knowing what it is you're trying to do, I can tell you that your button's onClick handler references a method name that isn't in your code. Judging by the names of your methods, I think you meant to put "buttonClicked" in there.
Nevermind, looks like you changed it while I was typing.
Instead of v.color = rgb(0,255,255); use v.style.color = "#0ff".
Related
I have this function that alerts the user when their amount of "moonstone" is 10. However, for various reasons, I would like the if statement to be outside the function. When I do this though, the alert doesn't work. Could someone please explain and post a fix for it?
<!DOCTYPE html>
<html>
<img id="game-board" onclick="totalCount()" class="game-board" src="https://pics.clipartpng.com/thumbs/Mars_PNG_Clip_Art-3002.png"></img>
<h2 id="counts">Moonstone:</h2>
<script>
let stone = 0;
function totalCount() {
let newCounts = stone++;
document.getElementById('counts').innerHTML= "Moonstone:"+ newCounts;
}
if (newCounts == 10){
alert('10');
}
</script>
</html>
What does work, but that I don't want to use, is
<DOCTYPE html>
<html>
<img id="game-board" onclick="totalCount()" class="game-board" src="https://pics.clipartpng.com/thumbs/Mars_PNG_Clip_Art-3002.png"></img>
<h2 id="counts">Moonstone:</h2>
<script>
let stone = 0;
function totalCount() {
let newCounts = stone++;
document.getElementById('counts').innerHTML= "Moonstone:"+ newCounts;
if (newCounts == 10){
alert('10');
}
}
</script>
In your code you calling the totalcount() function on onclick event so whatever inside the totalcount() function will executed and code outside the totalcount() function will not execute
I'm not entirely clear why you wouldn't want the if test within the function. But, there is something that you could do:
const counter = {
value: 0,
addOne: function() {
this.value++;
if (this.value > 10) {
alert("Too many");
this.value--;
} else {
document.getElementById("counts").innerHTML = "Moonstones: " + this.value;
}
}
}
function updateCounter() {
counter.addOne();
}
<button onclick="updateCounter();">Add</button>
<div id="counts"></div>
This creates the counter as an object and includes an if test on a addOne function directly attached to that object. Whenever the updateCounter() function is called, the addOne function updates the counter value and checks to see if it has passed 10. If it has, the user gets and alert, otherwise the "counts" element gets updated.
But, as others have said, there is no real reason why an if test shouldn't be part of a function - perhaps you could explain your reasons for that requirement?
Just don't know why this piece of code is not working: (onClick not working, click() is working (using console))
function click(ID)
{
if(cost[ID] <= currency[costID[ID]])
{
currency[costID[ID]] -= cost[ID];
currency[ID] += buyamout[ID];
document.getElementById(x[costID[ID]]).innerHTML = "<center>"+(Math.round(notyfication(currency[costID[ID]])*100)/100)+not+"</center>";
document.getElementById(x[gainID[ID]]).innerHTML = "<center>"+(Math.round(notyfication(currency[gainID[ID]])*100)/100)+not+"</center>";
}
}
...'<button onClick="click('+i+');">'+button+x[i]+'</button>'
this gives output <button onClick="click(0);">Make DNA</button>
and after clicking button nothing happens.
There could be a namespace conflict with your click. Use another name like button_click below
var i = 0;
var button = "Make ";
var x = [['DNA']]
document.writeln('<button onclick="button_click('+i+');" >'+(button+x[i])+'</button>');
function button_click(ID) { // notice the function name change
alert(ID);
}
Code below not working:
var i = 0;
var button = "Make ";
var x = [['DNA']]
document.writeln('<button onclick="click('+i+');" >'+(button+x[i])+'</button>');
function click(ID) { // the function name click may have been used already
alert(ID);
}
indeed onclick="click('+i+');" executes the javaScript code between the double brackets: click('+i+');: it calls the javaScript click() function, but this does not work if you declare function click() and someone else did that elsewhere in javaScript code.
if onClick is not working you can also use addEventListener will do the same job.
for e.g.
element.addEventListener('click', function() { /* do stuff here*/ }, false);
To answer your question you must do the following.
Change:
onClick="click(0)"
To:
onclick="click(0)"
That will most probably fix your problem.
<IMG onmouseover="document.swap2.src='http://www.grlf.com/pics/png';" id="brewmp" alt=Brew src=changeOSImage() width=26 height=24>
function changeOSImage() {
var mp_os = "x";
if (mp_os) == "Brew MP") {
document.getElementById("brewmp").src = "http://www.greengo-cellular.com/ebay_files/images/features_n_02.png";
} else {
document.getElementById("brewmp").src = "http://www.greengo-cellular.com/ebay_files/images/features_02.png";
}
};
For some reason instead of changing the url, the url displays the function name inside of it (therefore leading to nowhere). What have I done wrong?
You can not specify a function at the src attribute of an image.
Try putting the changeOSImage() function at the onload event of the document, or calling it from some other function.
As already mentioned, the src of your image cannot be a function. Also I cannot see what document.swap2 actually refers to in your code. try something like
<img id="brewmp" src="http://www.grlf.com/pics/png" />
<script>
window.onload = (function(){
var mp_os = 'x';
document.getElementById('brewmp').onmouseover = (function(){
this.src = 'path/to/different/image';
});
});
</script>
I'm not sure what mp_os is referring to in your initial code as it's set as x and you never change it, plus it is defined within the scope of your function which means it will always be 'x' in this case.The above should give you a good starting point to add your "if" statement into though, but you should declare var mp_os outside of the function
As noted in the other answers, you have an extra ) in your if statement. Try this:
Example: JsFiddle
JavaScript (added inside <head></head>):
<script>
var mp_os = '';
function changeImage(){
if (mp_os == "Brew MP") {
mp_os = "x";
document.getElementById("brewmp").src = "http://png-5.findicons.com/files/icons/75/i_like_buttons_3a/512/perspective_button_stop.png";
} else {
mp_os = "Brew MP";
document.getElementById("brewmp").src = "http://icons.iconarchive.com/icons/mazenl77/I-like-buttons-3a/512/Perspective-Button-Go-icon.png";
}
}
</script>
HTML:
<img onmouseover="changeImage()" onmouseout="changeImage()" id="brewmp" alt="Brew" src="http://png-5.findicons.com/files/icons/75/i_like_buttons_3a/512/perspective_button_stop.png" width="20%">
Can someone help me get started with a button timeout feature. All I want is a button (when clicked) it becomes inactive for 2 seconds. After which it is active again.
<input type="button" value="click" id="click" onclick="foo(this);"/>
function foo(obj) {
obj.disabled = true;
setTimeout(function() {
obj.disabled = false;
}, 2000);
}
LIVE DEMO
window.setTimeout on MDN:
Executes a code snippet or a function after specified delay.
Start of with:
<button>Click me!</button>
Add an event:
<button onClick="...">Click me!</button>
Now we need to put something in place of that ....
this can be used to mean "the button that was just clicked"
this.disabled can be set to true or false to disable (or re-enable) the button.
setTimeout(function() {...},2000); executes the anonymous function after two seconds have passed (or as near as the timer resolution allows).
Again, need to put something in the .... I've already told you how to re-enable the button.
Although, since this isn't terribly reliable inside anonymous functions, it's probably better to start with var t = this; and use t to mean the button.
With all that in place, you have:
<button onClick="var t = this; t.disabled = true; setTimeout(function() {t.disabled = false;},2000);">Click me!</button>
Done. I hope this explanation was helpful.
PS. To those who are against inline event handlers:
This is an example
The OP is a beginner
An inline event is good enough
The function setTimeout allows you to specify a function to be called after an amount of milliseconds has passed. In this case, I passed in an anonymous function, that is, a function that does not have a name that is used for the sole purpose of re-enabling my button after 2 seconds.
var mybutton = document.getElementById("mybutton");
mybutton.onclick = function() {
mybutton.disabled = true;
setTimeout(function() {
mybutton.disabled = false;
}, 2000);
};
Live example
You can use setTimeout() function in javascript. Something like
<html>
<head></head>
<body>
<input id="test" type="submit" value = "clickme" onclick="deactivatefunc()">
<script type="text/javascript">
function deactivatefunc()
{
var btn = document.getElementById("test");
btn.disabled = true;
var mytimer = setTimeout(activate,2000);
}
function activate () {
var btn = document.getElementById("test");
btn.disabled = false;
}
</script>
</body>
</html>
I noticed my users sometimes click the buttons twice, maybe no one told them one click is enough.
What's the best way to prevent the double-click?
I basically hide the button and show a "loading" gif, but that apparently is not enough...
Usually disabling/hiding/replacing the button should work. If they are real fast, try setting a variable to false when your script starts, return if it's true, set it to true after the first click.
var alReadyClicked = false;
function click(){
if (alreadyClicked)
return false;
alreadyClicked = true;
}
Don't forget to set it to false when the user can click again.
If they are clicking fast enough to fire the double click event, return false.
ondblclick="return false"
EDIT: This will not cancel the single click event so problem would still exist.
I just found out the jQuery funcion .one(), that may be useful great for this kind of purpose! great!
The equivalence to JQuery .one() may be the once option on AddEventListner like:
function doSubmit () { /* your code */ }
btn = document.getElementById ('foo');
btn.addEventListener ('click', doSubmit, {once: true});
Reference: javascript - JS equivalent for jQuery one() - Stack Overflow
Another example using a flag
<!DOCTYPE html>
<html>
<head>
<meta charset=utf-8 />
<title>test dbl click</title>
</head>
<body>
<button id="btn1">Click Away</button>
<div id="out"></div>
<script type="text/javascript">
function addMessage( msg ){
document.getElementById("out").innerHTML += (new Date().toTimeString()) + " : " + msg + "<br/><br/>";
}
function singleClick(){
addMessage( "single");
}
function addDoubleClickProtection( element, fncToCall ){
var isClicked = false;
var timer = null;
element.onclick = function(){
if(!isClicked){
isClicked = true;
timer = window.setTimeout( function(){ isClicked = false; }, 200);
return fncToCall();
}
}
}
addDoubleClickProtection( document.getElementById("btn1"), singleClick );
</script>
</body>
</html>
Simple method by counting the submit button click and with minimum decoration will:
<script>
var click_count = 0;
function submit_once () {
document.forms.A.elements.cmd.forEach(
function(e,i,l){e.style.color="#888";});
return (click_count++ > 1);
}
function reset_count () {
document.forms.A.elements.cmd.forEach(
function(e,i,l){e.style.color="unset";});
click_count = 0;
}
</script>
<form name="A">
<button type="submit" name="cmd" value="doAdd"
onclick="return submit_once();">Do add</button>
<button type="submit" name="cmd" value="doDel"
onclick="return submit_once();">Do delete</button>
</form>
You can create a util function once which will take CB function. And all logic handles seamlessly. You don't have to create a global variable to count or update.
function once(cb) {
let once = false;
return (...args) => {
!once && cb(...args);
once = true;
};
}
// How to use it.
// Create/bind function
const log = once((data) => {
console.log(data);
});
// Use it
Promise.resolve("hellowold").then(log).then(log);
Above line print only once.