I am very new to JavaScript and programming in general. I am currently in a little pickle with some code that I am playing around with, and I am wondering if anyone can give me some advice.
Background:
The code I am working with is rather simple; There is a clock with the current time running on setInterval to update by the second.
Below the clock there is a button that reads “Stop,” and when pressed, it will clear the Interval and the button will then read “Start.” If the button, which reads “Start” is pressed again, it will continue the clock timer in its current time. So basically this one button toggles the interval of the clock, and depending on which state it is, the button will read “Start” or “Stop.”
W3Schools: JS Timing is where I am originally referencing when creating the code I am working with. This is where I am learning about how setInterval and clearInterval works. I also took some of the code in the examples and adjusted it so I can try to make the clock timer toggle off and on.
Code:
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
https://jsfiddle.net/dtc84d78/
Problem:
So my problem with the code is that the button toggles from a “Stop” button to a “Start” button, but the clearInterval is not applying to the Variable with the setInterval.
I have googled similar problems in SO, such as this one, and I followed their advice, and still nothing. After hours of trying to figure out, I decided to just copy and paste some example from W3Schools straight to jsFiddle, and that didn’t even work (included in jsfiddle link)?
I am really just going crazy on why anything with clearInterval() is not working with me? Could it be my computer, browser or anything else? I am coming to SO as my last resource, so if anyone can give me some guidance to this problem, I will name my first child after you.
Thank you in advance.
Extra Info:
I am currently working on a Mac desktop, using Komodo to write the code, and I am using Google Chrome to preview the code.
UPDATE:
I mentioned this in the comments, but coming in the code was in an external .js file. The .js file was then linked in between the head tags, and right before the end body tag.
<head>
<meta charset="utf-8" />
<title>Program</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/program-05.css">
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
</head>
<body onload="checkCookies(); setTimeout(function() { func11() }, 5000);">
. . . code for stuff
. . . code for clock timer
. . . code for other stuff
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
</body>
After #Matz mentioned to stick the clock timer js code in the head section, the code worked great! This is what it looks like so far in the head section.
<head>
<meta charset="utf-8" />
<title>Program</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/normalize.css">
<link rel="stylesheet" href="css/program-05.css">
<script type="text/javascript" src="scripts/program-05.js">
/* <![CDATA[ */
/* ]]> */
</script>
<script>
///*
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
//*/
</script>
</head>
Though this works great, I now want to figure out as to why the clock timer js code works when it is directly in the head section as compared to keeping it in the external .js file (with the external file being linked in the doc)? What can I do to make it work within the external file?
Problem:
This is because the default Load Type is set to onLoad which is wrapping your javascript code in window.onload = function() {} hence the scope of your function was getting limited to the onload function and it wasn't available outside:
Solution:
Click on the Javascript setting in the Javascript section of the Fiddle, change it to No wrap - in body and it will work since this will now place your Javascript code in the body tag.
Additional Note:
Your code is also working via StackOverflow snippet:
/*My Problem*/
var clock09 = window.setInterval(myTimer09, 1000);
function myTimer09() {
var d = new Date();
var t = d.toLocaleTimeString();
document.getElementById("req09").innerHTML =
"<h1>" + t + "</h1>";
}
function toggle10() {
var button = document.getElementById("button10").innerHTML;
if (button == "Stop") {
window.clearInterval(clock09);
document.getElementById("button10").innerHTML = "Start";
} else {
clock09 = window.setInterval(myTimer09, 1000);
document.getElementById("button10").innerHTML = "Stop";
}
}
/*W3S Problem*/
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById("demo").innerHTML =
d.toLocaleTimeString();
}
<!-- My Problem -->
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
<hr>
<hr>
<!-- W3S Problem -->
<p id="demo"></p>
<button onclick="clearInterval(myVar)">Stop time</button>
Recommendation
Separation of concerns
I'll recommend you moving your javascript code in the external file and later include them in your HTML using script tag. So for example, you moved your code in app.js then include that in your HTML as:
<!-- make sure the path here is relative to the current HTML -->
<script src="./app.js"></script>
One way to fix the timer starting and stopping is to move the javascript in between the HEAD tags so the functions are declared by the time the html loads. I made this work:
<html>
<head>
<title>Stuff</title>
<script >
var clock09 = window.setInterval(myTimer09, 1000);
.... your code
</script>
</head>
<body>
<span class="center" id="req09"></span>
<button type="button" id="button10" onclick="toggle10()" class="button">Stop</button>
</body>
</html>
You are declaring a new date variable in the myTimer09 function, so every time it is called, it shows the current time. You should declare the time outside the function, then pass it to the function. When you stop the timer, you should save the time value so that you can restart with that value.
This seems to be an issue with JSFiddle.
The onclick handler is looking for window.toggle10 which isn't actually defined (check for the error in the console).
It seems that this is something others have seen with JSFiddle
I've C&Ped your code in to a JSbin and it works as described!
Related
I'm trying to get the date to appear in an empty paragraph with an ID when I click on a button. So far no luck. Don't mind if I cant get it to appear in the paragraph but just want to know how to make it appear when I click the button thanks in advance.
sorry if its a dumb one,
I have got the alert working on click but just can not seem to figure this one out
<!DOCTYPE html>
<html>
<head>
<title>Lets Practice Some Code</title>
<link rel="stylesheet" type="text/css" href="/Users/Matteveli/Desktop/javascript practice/style/style.css">
</head>
<body>
<div><h1 id="topTitle"> Time and date Test</h1></div>
<div><button id="alerter">click Me to make an alert pop up.</button></div>
<p id="empty"
></p><div><button id="timeAndDate">click Me to display time and date</button></div>
<script type="text/javascript" src="/Users/Matteveli/Desktop/javascript practice/javascript/funtionality.js"></script>
</body>
<footer>
</footer>
</html>
var alerterButton = document.getElementById("alerter");
var dateButton = document.getElementById("timeAndDate");
var emptyP = document.getElementById("empty");
var d = new Date();
// for the first click that we have working.... " THE ALERT "
//a link to function was called then the function was made
// as below
alerterButton.onclick = myClickHandler;
function myClickHandler() {alert("the document was clicked")};
/// TIME AND DATE ???
dateButton.onclick = emptyP.innerHTML=d;
function showMeTheDate() {emptyP.innerHTML+d};
any help greatly appreciated.
thanks in advance.
Here an example: http://jsfiddle.net/sckjnx7t/2/
The key is engage function and event, in this case onclick, then, you could do:
dateButton.onclick = function(){
//code here
};
or:
dateButton.onclick = showMeTheDate();
function showMeTheDate() {
//code
};
dateButton.onclick should be a function. So, you should do
dateButton.onclick = () => { emptyP.innerHTML= d.getDate() }
Only edit your event handler function, and set pharagraph's innerHTML to d.getDate().
function myClickHandler() {
alert("button was clicked!");
emptyP.innerHTML = d.getDate();
}
You need to stay the function workers in same scope. Without this approach, the latest eventHandler function will be used for all time, because other (last) functions' functionality won't be.
First, I am completely new to coding and have been using self-teaching tools to learn Javascript in my free time. I've learned enough to start building my own projects. My first attempt is to build a randomizer (in this case, random restaurant names). The Javascript works through my tests in the console as do the buttons. However, I cannot seem to get the .innerHTML to work and I'm not sure what I'm missing. I've done several searches here and none of the solutions I've found seem to be working.
The error I'm getting is listed in the title and it is appearing at line 29.
Here is Javascript:
var randomRestaurant = {
restaurantName: [],
findRestaurant: function() {
var restaurantName = Math.random();
if (restaurantName < 0.20) {
this.restaurantName.push("China Taste");
}
else if (restaurantName < 0.40) {
this.restaurantName.push("Pizza Johns");
}
else if (restaurantName < 0.60) {
this.restaurantName.push("Liberatore's");
}
else if (restaurantName < 0.80) {
this.restaurantName.push("Bill Bateman's");
}
else {
this.restaurantName.push("R&R Taqueria");
}
},
clearRestaurant: function() {
randomRestaurant.restaurantName.splice(0, 1);
}
};
var randomRestaurantButton = document.getElementById('randomRestaurantName');
randomRestaurantButton.addEventListener('click', function() {
randomRestaurant.findRestaurant();
document.getElementById("restaurantNameDisplay").innerHTML = randomRestaurant.restaurantName[0]; //<--line 29
});
var randomRestaurantButton = document.getElementById('refreshRestaurant');
randomRestaurantButton.addEventListener('click', function() {
randomRestaurant.clearRestaurant();
randomRestaurant.findRestaurant();
document.getElementById("restaurantNameDisplay").innerHTML = randomRestaurant.restaurantName[0];
});
And here is my HTML:
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div><h1>Random Restaurant!</h1>
<button id="randomRestaurantName">Click me for a random restaurant!</button>
</div>
<br>
<h2="restaurantNameDisplay"></h2="restaurantNameDisplay">
<div>
<br>
<button id="refreshRestaurant">Nah. Give me another one.</button>
</div>
</body>
<script src="script.js"></script>
</html>
Thanks for your help and hopefully it's not due to something stupid like a typo.
There are some problems here.
the h2 tag id should be
<h2 id="restaurantNameDisplay"></h2>
your buttons are set on the same variable name, change the second to
var refreshRestaurantButton = document.getElementById('refreshRestaurant');
refreshRestaurantButton.addEventListener('click', function () {
randomRestaurant.clearRestaurant();
randomRestaurant.findRestaurant();
document.getElementById("restaurantNameDisplay").innerHTML = randomRestaurant.restaurantName[0];
});
If it's still not working, you should call your script after the page load event.
so insert your javascript code to a function (e.g. "myFunc()") and change your html body tag to:
body onload="myFunc()">
Most probably this line <h2="restaurantNameDisplay"></h2="restaurantNameDisplay"> should be
<h2 id="restaurantNameDisplay"></h2>
Yesterday, I was informed about setInterval to perform a task or function after a certain number of milliseconds. I have the interval working in my code, but each time it creates a new text line with the date. I want it to replace the previous one after each interval has ended. I tried fixing this by defining the text and date as a variable to be called, but that doesn't work either. Also, for anybody who is interested, here's the link to my question yesterday, which received very helpful responses.
<html>
<head>
<title>Time Stuff Page</title>
</head>
<link href="main.css" rel="stylesheet" type="text/css">
<body>
<!-- adding color style for demo date buttons via CSS style tag->
<style type="text/css">
#demo {
color:red;
}
#demo2 {
color:blue;
}
</style>
<!-- Display date in paragraph -->
<button onclick="getElementById('demo').innerHTML=Date()">The time is? (from innerhtml)</button>
<p id="demo"></p>
<!-- Display date by calling a JS function -->
<button onclick="displayDate()">The time is? (from javascript)</button>
<p id="demo2"></p>
<!-- Display date inside "this" button -->
<button onclick="this.innerHTML=Date()">The time is? (display in button)</button>
<p></p>
<script language="javascript">
function displayDate() {
document.getElementById("demo2").innerHTML = Date();
}
var savedate = Date();
document.write("You loaded the page at: "+savedate);
//constantly updated date();
constantDate = function() {
var date = Date();
var timetext = "<br />Updated time is: "+date;
document.write(timetext);
}
function checkDate() {
setInterval(function(){ constantDate(); }, 10);
}
checkDate();
</script>
</body>
</html>
Create similar function to displayDate:
function displayDate2() {
var timetext = "Updated time is: "+Date();
document.getElementById("demo3").innerHTML =timetext;
}
You also need to add another paragraph to the body:
<p id="demo3"></p>
The problem is that your JavaScript file is calling the "checkDate()" function as soon as it runs. This means it will run the "constantDate()" function, and this function is using document.write to output the result.
Therefore it will be spamming your document with that output, instead of inserting it in a div. Set it to insert in a div inside the "constantDate()" function like this, and then create the div, and everything should be fine:
constantDate = function() {
var date = Date();
var timetext = "<br />Updated time is: "+date;
document.getElementById("demo3").innerHTML = timetext;
}
And create the div class:
<p id="demo3"></p>
Also, it's usually, like almost always, better to separete your HTML code and JavaScript code, so instead of adding JS code or functions to your "onclick=" property on the button's HTML, add click events in your JS like so:
HTML:
<button id="button2">The time is? (from javascript)</button>
JavaScript:
/* On click event for button 2 */
var button2 = document.getElementById('button2');
button2.onclick = function() {
displayDate();
}
Check this JS Fiddle I've done for you: http://jsfiddle.net/filipetedim/t0to0hL8/
Alright. As a part of a personal project to get familiar with Javascript, css and html outside of tutorials I've decided to try to create a cookie clicker like game for fun. However, I'm a bit stuck on the DOM manipulation.
var multiplier=1;
var money=5;
var moneyTotal=money*multiplier;
$(document).ready(function() {
$('div #button').click(function() {
var money++;
});
});
document.getElementById('counter').innerHTML = moneyTotal;
What I'm trying to do is having some text in my html index page, that changes whenever you click the div with the ID button. That piece of text has the id counter. But I can't seem to make this work, and I'm starting to get really frustrated after having this problem for 4 hours and not finding a solution. I have a feeling I'm missing some very obvious syntax, but I have no idea on what.
Edit:
Alright I changed the code so that it looks like this now:
var multiplier=1;
var money=5;
$(document).ready(function() {
$('#button').click(function() {
money++;
$('#counter').html(money * multiplier);
});
});
However it still won't target my div with the ID counter.
Here's the index.html, but I'm 99% sure there's no syntax errors there, and I have no idea on why it won't work.
<!DOCTYPE html>
<html>
<head>
<script type='text/javascript' src='script.js'></script>
<link rel='stylesheet' type='text/css' href='style.css'/>
</head>
<body>
<div id="button"></div>
<div id="counter">0</div>
</body>
</html>
Edit:
This is the final solution, thanks again everyone!
var mp = 1
var money = 0
$(document).ready(function() {
var localMoney = localStorage.getItem("money");
var localmp = localStorage.getItem("mp")
$('#moneycounter').click(function() {
money++;
$('#counter').html(money * mp);
});
});
I'm not sure what you're expecting it to do...
But var money +1 is wrong. Should be money++
Then you have to recalculate moneyTotal, and set it into the innerHTML at that point.
You need to run the function to update your div everytime you click!
var multiplier=1;
var money=5;
var moneyTotal=money*multiplier;
$(document).ready(function() {
$('div #button').click(function() {
money++;
updateElement();
});
});
function updateElement(){
document.getElementById('counter').innerHTML = moneyTotal;
}
I am trying to create a basic image rotate. I have my images stored locally by name in a folder called comics. each comic name is comic_(plus the number). It wont do anything when I click my buttons. It wont even disable my previous button. Please help. Thank you guys.
Here is my JS/Jquery...
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
//declare my variables
var comic_img = $('#comicpane').find('img')
var current_comic_number = parseInt(comic_img.attr('class').replace('comic_',''))
var prev_comic = current_comic_number - 1;
var next_comic = current_comic_number + 1;
});
if (current_comic_number == 1){
//disable the prev button
$("#prev").attr('disabled','disabled');
//When the user clicks on a nav item
$(".nav_link").on('click')function(){
//Get the button they clicked
current_button = $(This);
if (current_button.attr('id')) == 'next'
{
comic_img.attr('class','comic_') + next_comic + ".jpg";
comic_img.attr('src','comics/comic_1') + next_comic;
//change variables to reflect current comic
current_comic_number +=1;
next_comic +=1;
prev_comic +=1;
}
//Only other option
else
{
comic_img.attr('src','comics/comic_1') + prev_comic + '.jpg';
comic_img.attr('class','comic_') + prev_comic;
//Change variables to reflect comic
current_comic_number -=1;
next_comic -=1;
prev_comic -=1;
}
//If comic number is less or equal to 1 and prev button is Not disabled, it needs to be disabled.
if (current_comic_number <=1 && !$('#pev').attr('disabled','disabled'))
{
$('#prev').removeAttr('disabled')
}
}
}
</script>
Here is my HTML...
<html>
<head>
<title>SRS Comic Zone</title>
<link rel="stylesheet" href="srscomiczone.css" media="screen">
</head>
<body>
<div id="header">
<img id="header" src="HeaderPicture.png" align=center>
</div>
<div class="comiczone" id="comicpane" align=center>
<img class="comic_1" src="comics/comic_1.jpg">
</div>
<div id="comicNav" align=center>
<button id="prev" class="nav_link">Previous</button>
<button id="next" class="nav_link" >Next</button>
</div>
</body>
</html>
few mistakes,
1) this is how you call a click event
$(".nav_link").on('click',function(){
....
and not
$(".nav_link").on('click')function(){ //replace this with above code
you might also need to delegate your selector if it is added dynamically.....
2)
current_button = $(This);
should be
current_button = $(this);
3) also, notice..if you are using jquery 1.6+, use prop() instead of attr()
$("#prev").prop('disabled',true);
instead of
$("#prev").attr('disabled','disabled');
4) add all your codes inside document.ready $(document).ready(function(){ //here }); function and not outside.
5) most important, you either have to include the script (js file) inside you html page. or paste all your script codes inside <head> tag of your HTML file
Also this stuff should be wrapped by:
$(document).ready(function() {
$(".nav_link").on('click',function(){
...
});
not just your var declarations.
Your code is trashy. Better use tool like JS Hint (or other JS validator, or even Chrome/Firefox with web console) to actually make sure code can even run.
Here are (some) of the issues with it:
you're missing semicolons
your .ready() function is (as I believe) ending prematurely
you're doing click handling wrong (pointed out by #bipen)
your if statements are messed up
you (probably) haven't included scripts into the HTML document
Ad 1
Missing semicolon here:
var comic_img = $('#comicpane').find('img')
Ad 2
current_comic_number is a local variable in $.ready(), but it's used outside of this function
Ad 3
It's not valid JS (see #bipen's answer):
$(".nav_link").on('click')function(){
Ad 4
It's not valid if statement:
if (current_button.attr('id')) == 'next'
it should be:
if (current_button.attr('id') === 'next')
Ad 5
Use <script> tag only inside *.html file, not in *.js. On example:
<script src="main.js"></script>
Then, put all of your JS code into main.js file.