Javascript - novice script not working - javascript

could someone explain why this script isn't working? I tried to figure it out for long time, but I didn't manage to do it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<script>
function Xyz() {
var x = 0;
}
function Switch() {
if (x == 0) {
document.body.style.backgroundColor = "black";
x = 1;
}
else {
document.body.style.backgroundColor = "white";
x = 0;
}
}
</script>
</head>
<body>
<button type="button" onclick="Switch()">Click me</button>
</body>
</html>

if(x==0)
Since x doesn't exist, it throws a ReferenceError here and aborts the rest of the function.
You need to declare x first.
This:
function Xyz()
{
var x=0;
}
Creates a variable x that is local to the function and
Is never called anyway

You need to define variable x. I used hoisting in this example.
<!DOCTYPE html>
<html>
<head>
<script>
function Xyz()
{
var x=0;
}
function Switch()
{
if(x==0)
{
document.body.style.backgroundColor="black";
x=1;
}
else
{
document.body.style.backgroundColor="white";
x=0;
}
}
var x;
</script>
</head>
<body>
<button type="button"onclick="Switch()">Click me</button>
</body>
</html>

Issue is You need to declare a variable before using it.
function Switch()
{
if(x==0) // this x is not defined.
{
document.body.style.backgroundColor="black";
x=1;
}
else
{
document.body.style.backgroundColor="white";
x=0;
}
}
Since you need to use the same variable to update it with each click , define it outside function.
<!DOCTYPE html>
<html>
<head>
<script>
var x = 0;
function Xyz()
{
var x=0;
}
function Switch()
{
if(x==0)
{
document.body.style.backgroundColor="black";
x=1;
}
else
{
document.body.style.backgroundColor="white";
x=0;
}
}
</script>
</head>
<body>
<button type="button"onclick="Switch()">Click me</button>
</body>
</html>

Related

I can't make my timer on javascript to redirect to another page

I'll try to be brief.
I know practically nothing about programming, I'm trying to learn by myself for a personal project.
I'm trying to do something like a timer which, when it reaches 0, redirects to another page. What I managed to build so far is this:
<!DOCTYPE html>
<html>
<body>
<input type="text" id="txt">
<body onload="startCount()">
<script>
var c = 10;
var t ;
var timer_is_on = 0;
function timedCount() {
document.getElementById("txt").value = c;
c = c - 1;
t = setTimeout(timedCount, 1000);
}
function startCount() {
if (!timer_is_on) {
timer_is_on = 0;
timedCount();
}
}
</script>
</body>
</html>
When I try it on chrome, it doesn't run or it instantly jumps to the other page.
If you could tell me what's wrong, or how to fix it, it would be wonderful.
Now, I just discover(?) that I lost the other part that redirects. I used this
<script>
function myFunction() {
location.replace("https://www.w3schools.com")
}
</script>
I don't know if I explained this correctly, but I appreciate the help!!
Thanks!
EDIT: Thanks everyone for the answers!! It's fixed now.
I think what you are trying to do is update the value of timer in the input box every second until it reaches zero, and after that redirect to another URL.
This would do the needful:
(I have removed some unused code which is not required)
<!DOCTYPE html>
<html>
<body>
<input type="text" id="txt" />
<body>
<script>
var timeLeft = 10;
function timedCount() {
document.getElementById("txt").value = timeLeft;
if (timeLeft) {
setTimeout(function(){
timeLeft--;
timedCount();
}, 1000);
} else {
window.location = 'https://w3schools.com';
}
}
timedCount();
</script>
</body>
</html>
In the timedCount check if the value of C is bigger than 0 and run setTimeout otherwise (smaller or equal 0) redirect
Also I think you meant to update timer_is_on to 1 here:
function startCount() {
if (!timer_is_on) {
timer_is_on = 0; //Shouldn't this be set to 1?
timedCount();
}
}
I believe this could be one of the ways to do it.
<!DOCTYPE html>
<html>
<body>
<input type="text" id="txt">
<body onload="startCount()">
<script>
var c = 10;
var t ;
var timer_is_on = 0;
function timedCount() {
document.getElementById("txt").value = c;
c--;
t = setTimeout(timedCount, 1000);
if(c <= 0) {
window.location.href = "https://www.w3schools.com/";
}
}
function startCount() {
if (!timer_is_on) {
timedCount();
}
}
</script>
</body>
</html>

how to add animation in string

I want add rotation in my string for that i have set interval but its not getting me as i want. it works only for one time when i reload the browser. So what should i add for continuing the function.
this is my code
HTML
<html>
<head>
<title>JavaScript basic animation</title>
<script type="text/javascript">
</script>
<script type="text/javascript" src="myfunction_2.js"></script>
</head> <body onload="shubham()">
<div id="target">w3resource</div>
<button >click</button>
</body>
</html>
javascript
function shubham()
{
var x=document.getElementById('target').textContent;
var y=x.split('');
var z=y[0];
var m=y[y.length-1];
setInterval(function ()
{
document.getElementById('target').innerHTML = m+x.substring(0,8);
},500);
}
The problem with your code was that the variables were initialized once, and whenever, the setInterval function was called, there was no change in variables and hence the result remained the same which appeared as function only executed 1 time only.
Move your variables inside the setInterval function.
setInterval(function() {
var x = document.getElementById('target').textContent;
var y = x.split('');
var z = y[0];
var m = y[y.length - 1];
document.getElementById('target').innerHTML = m + x.substring(0, 8);
}, 500);
<div id="target">w3resource</div>
you mean something like this
<html>
<head>
<title>JavaScript basic animation</title>
</head>
<body onload="shubham()">
<div id="target">w3resource</div>
<button onclick="shubham()">click</button>
</body>
</html>
<script>
function shubham() {
var x = document.getElementById('target').textContent;
var y = x.split('');
var z = y[0];
var m = y[y.length - 1];
setInterval(function () {
document.getElementById('target').innerHTML = m + x.substring(0, 8);
}, 500);
}
</script>

Changing color code doesn't work

function color(){
var color = "#"
for(var i = 0; i<6; i++){
color += Math.floor((Math.random()*16)).toString(16);
};
document.getElementsByTagName('body')[0].style.backgroundColor = color;
}
function change(){
setInterval(color(), 1000);
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id='button' onmouseover="change();" style='width:50px; height:50px; margin-left:auto;'>click</button>
<script type="text/javascript" src='js.js'></script>
</body>
</html>
I tried to make the auto changing background coding.
I want to change the background color every 1 second.
but it just change color once when i put my mouse on.
what is the problem?
You're calling the function, not referencing it in the setInterval call.
Change it to
setInterval(color, 1000);
FIDDLE
When you add the parentheses to a function, it's called, and the returned result, which is always undefined unless something else is defined in the called function, will be returned.
What you're doing is the same as
var fn = color(); // returns undefined
setInterval(fn, 1000); // undefined, 1000
Here's a working snippet.
What I changed was
onmousehover was replaced with oneclick() (since it says click on the button)
In the setInterval function call, color doesn't need the brackets
function color(){
var color = "#"
for(var i = 0; i<6; i++){
color += Math.floor((Math.random()*16)).toString(16);
};
document.getElementsByTagName('body')[0].style.backgroundColor = color;
}
function change(){
setInterval(color, 1000);
}
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<button id='button' onclick="change();" style='width:50px; height:50px; margin-left:auto;'>click</button>
<script type="text/javascript" src='js.js'></script>
</body>
</html>
</html>
Here is a working example
<body>
<button id='button' onmouseover="change()" style='width:50px; height:50px; margin-left:auto;'>click</button>
</body>
<script>
function color() {
var color = "#"
for (var i = 0; i < 6; i++) {
color += Math.floor((Math.random() * 16)).toString(16);
};
document.getElementsByTagName('body')[0].style.backgroundColor = color;
}
function change() {
setInterval(color(), 1000);
}
</script>
Fiddle: https://jsfiddle.net/9cxw9jL0/
I have changes some code and you can find in plunker.
<https://plnkr.co/edit/sKpJQqRohICD63AQjgTx?p=preview>
Here is the solution for your problem
function colorchanger(){
setInterval(function(){
var letters = '0123456789ABCDEF'.split('');
var color = '#';
for (var i = 0; i < 6; i++ ) {
color += letters[Math.floor(Math.random() * 16)];
}
document.body.style.backgroundColor = color;
},300);
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title></title>
<link rel="stylesheet" href="">
</head>
<body>
<button onclick="colorchanger();" >Change Color</button>
</body>
</html>

One HTML button to invoke 3 functions consecutively

I am new to Javascript programming, and need some help.
I have one HTML button, and I want to invoke 3 functions.
The first time I click the button, I want to invoke function 1.
The next time I click the button, I want to invoke function 2.
The third time I click the button, I want to invoke function 3.
I was thinking that I could use if tests.
i++ when button is clicked,
if ( i == 1){ function1(); } .....
HTML
<button type="button" onclick="myFunction()">Hei</button>
Javascript
if(i == 1){
test1();
}
if(i == 2){
test2();
}
if(i == 3){
test3();
}
function test1() {
document.getElementById("print1").innerHTML = "test1";
}
function test2() {
document.getElementById("print2").innerHTML = "test2";
}
function test3() {
document.getElementById("print3").innerHTML = "test3";
}
This is just for testing/practice, so the code has no point
But I think there has to be another way.
Try this:
<button onclick="myFun(i)"></button>
in javascript,
function myFun(i) {
(i===0 && function1()) || (i===1 && function2()) || function3();
}
//Html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<button onclick="triggerFunc()">Click Me</button>
</body>
</html>
//Javascript
var obj = {
f1: function() {
alert('from f1');
},
f2: function() {
alert('from f2');
},
f3: function() {
alert('from f3');
}
};
window.flag = 1;
function triggerFunc() {
var flag = window.flag + 1;
if(flag > 3){
flag = 1;
}
window.flag = flag;
obj['f'+ flag]();
}
just check the jsbin link http://jsbin.com/dudubaxafu/edit?html,js,output
You can do like following code :-
HTML code :-
<button type="button" onclick="myFunction()">Hei</button>
javascript code :-
i = 1;
function myFunction()
{
if (i == 1)
{
i++;
test1();
}
else if (i == 2)
{
i++;
test2();
}
else if (i == 3)
{
i++;
test3();
}
}
function test1() {
document.getElementById("print1").innerHTML = "test1";
}
function test2() {
document.getElementById("print2").innerHTML = "test2";
}
function test3() {
document.getElementById("print3").innerHTML = "test3";
}
It may help you.
I would not recommend polluting the global namespace via window["i"], which limits you to only one such button.
I would use something like this:
function cycle(){
var i = 0;
var args = arguments;
return function(){
args[i]();
i++;
if(i>=args.length)
i = 0;
}
};
then you can use it like so:
document.getElementById("button1").addEventListener("click", cycle(
function(){
alert(1);
},
function(){
alert(2);
},
function(){
alert(3);
}));
Here's a fiddle sample:
https://jsfiddle.net/h6qsam8e/

Javascript SetTimeout chaining

This may be a simple problem but I can't seem to embed a variable parameter in a function for future execution. "alert" is the function I'd like to delay execution, with the parameter 0, 1, 2 etc
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script language="JavaScript">
var init = function init() {
for (var i = 0, max = 3; i < max; i++) {
var then;
then = (function(jj) {
return jj;
}(i));
var pp = function(jj) {
return alert(then);
};
setTimeout(function() {
pp();
}, then * 1000);
}
};
</script>
</head>
<body onload="init();">
<button onclick="init();"></button>
</body>
</html>
You didn't really ask a question so I'll assume any implementation that produces the results you were expecting is what you want.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<script language="JavaScript">
function createfunc(i) {
return function() { alert(i); };
}
var init = function init() {
for (var i = 0, max = 3; i < max; i++) {
var func = createfunc(i);
setTimeout(func, i * 1000);
}
};
</script>
</head>
<body onload="init();">
<button onclick="init();"></button>
</body>
</html>
This will alert a number, then wait a second and alert another number. Until 3 is reached:
var init = function() {
var counter = 0, //Start
max = 3 //End
var count = function() {
alert(counter) //Alert
if ( counter < max ) { //If we havent reached 3 then queue this function to be called again
window.setTimeout(function() {
count()
}, 1000)
}
counter++
}
count() //Start the counter
}
Here is a fiddle: http://jsfiddle.net/EXwH2/1/
You enclosed the first function in a closure but not the second, so you essentially set your pp var to the last iteration before setTimeout is called for the first time. What's your intent with the then variable? If you want to stagger the calls, each with their own value, you might want to put the call to setTimeout itself within its own closure:
var init = function init() {
for (var i = 0, max = 3; i < max; i++) {
(function (jj) {
setTimeout(function() {
alert(jj);
}, jj * 1000);
})(i);
}
};

Categories