Access value of variable from if statement Javascript with event onclick - javascript

I have the following snippet of code:
var j=4;
var x;
if(j>5){
x=8;
}else if(j<5){
x=1;
}
function write(){
document.write(x);
}
UPDATE: I am having a problem that when I have a button call the function write() it will not print out 1 when it is clicked, it will print out nothing. Calling the function write() separately works, but how do I get that to change for when it is called on by the onclick event?

You must call the function:
function write(){
document.write(x);
}
var j=4,
x;
if(j>5){
x=8;
}else if(j<5){
x=1;
}
write();
Here is a jsfiddle demo

Related

Function is not defined even though it is

I am coding a taximeter which is calculating the drive-expenses through the elapsed time. By clicking a button the standing below function "startDrive" will normally executed, but when I am clicking on my button the browser or console respectively is showing an error which is including the message "Uncaught ReferenceError: startDrive is not defined
at HTMLButtonElement.onclick (time.html:15:62)". I checked whether I mentioned the wrong Function in the "onclick" part in HTML but this is not the case. What I am doing wrong?
//global variables
let y = 3.9;
let reversal = 20;
//Main-function in which the sub-functions are be executed
function startDrive() {
document.getElementById('output1').innerHTML = y.toFixed(2) + "€";
interval();
}
//Calculating drive-expenses
function calculate() {
if(y < reversal) {
y += 0.14375;
}
else if(y > reversal) {
y += 0.103125;
}
document.getElementById('output1').innerHTML = y.toFixed(2) + "€";
}
//Fixed time in which "calculate()" will be executed
function interval() {
timerId = setInterval(calculate, 5000);
}
//Stopping interval
function stop() {
clearInterval(timerId);
}
<button onclick = "startDrive()">start!</button>
<output id = "output1"></output>
here
<button onclick = "startDrive">start!</button>
use startDrive() instead of startDrive
you can watch a sample at here.
It says startDrive is not defined, so it seems your function definitions are never executed.
If you put your code in a plain script tag inside head it works just fine:
https://codesandbox.io/s/great-joana-ubttg5?file=/index.html

window.onload called after returning from a event handler method

This code is for learning purpose in javascript.I have declared a global variable called num and initialized it to 30. Now this is increased on click of a plus button and is decreased on click of minus button.But when I click plus button twice.It alerts 31 twice instead of showing 31 first then 32.
When I debugged it on chrome I found out that the breakpoint hits 'var num=30' again once it executes the increase method which is called onclick of plus button.
So why after the return from method the window is reloading?Can someone please explain?Thanks in advance.My code is as below :
window.onload =initialize;
var num=30;
function initialize()
{
if(!document.getElementById) return;
var increaseButton = document.getElementById('plus');
increaseButton.onclick = increase;
var decreaseButton = document.getElementById('minus');
decreaseButton.onclick = decrease;
}
function increase()
{
num++;
alert(num);
}
function decrease()
{
num++;
alert(num);
}
Seems to work for me if the HTML is:
<button type="button" id="plus">+</button>
<button type="button" id="minus">-</button>
You would also want your decrease function to be:
function decrease()
{
num--;
alert(num);
}
JSFiddle: https://jsfiddle.net/OzymandiasII/L9h1xbsr/

JS onClick not working

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.

JavaScript generated HTML with onClick doesn't trigger function

The script below adds items to an array when you click the link, and generates a list of items as html output. You can see an example here: http://jsfiddle.net/dqFpr/
I am trying to create a function to delete items from the list. Not a difficult task with splice(), but somehow clicking the delete link doesn't trigger the test_function() function.
Can someone tell me what I am doing wrong, or show me another way of triggering the function? Your help is really appreciated ;-)
<script language="javascript">
$(document).ready(function() {
function test_function( number ) {
/* This function is not triggered, nothing works inside here!! */
}
});
var lines = [];
function update_list( lines ) {
var thecode = '';
for(var i = 0; i < lines.length; i++) {
thecode = thecode + lines[i] + ' <a onclick="javascript:test_function('+i+')" href="#">(delete)</a><br />';
}
$('div#display').html(thecode);
}
$('a#new').click(function() {
lines.push('another line');
update_list(lines);
});
</script>
<div id="display"></div>
Add a new line
Because in the text assigned to display's innerHTML, *test_function* is just plain text that is evaluated by the HTML parser. At that point, its scope is global, not within the IIFE passed to $(document).ready(). You can fix that by making the function global:
$(document).ready(function(){
window.test_function = function (number) {
// do stuff
}
....
});
or
var test_function;
$(document).ready(function(){
test_function = function (number) {
// do stuff
}
....
});
Or whatever method you like to get access to the function. But while it is declared inside an anonymous function's scope, you can only get access to it from a function that has a closure to the variables in that scope.

Color-cycling an element not working?

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".

Categories