I'm a bit lost on DOM manipulation - javascript

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;
}

Related

clearInterval() not working on clock timer with JavaScript

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!

.innerHTML: Cannot set property 'innerHTML' of null

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>

Hide drop down list on conditional

I am simply trying to hide a select list/drop down list on an html page. I am not trying to hide the options in the select list, just the select list overall. I am having the hardest time for some unknown reason. I cannot figure out how to do this.
HTML
<HTML>
<head>
<title>Test</title>
<script type="text/javascript">
var myVal = 10;
if (myVal = 10) {
document.getElementById("contracts").style.visibility="hidden";
}
</script
</head>
<body>
<select id="contracts" name ="contracts" style="width:99%;height:50px"></select>
</body>
</html>
As simpel as can be, yet I cannot figure out how to hide the select list. It's still present on my page. This example is actually hiding the values in my select list but not the overall select list. Does anyone know how to accomplish this? I am out of ideas. Thanks in advance for your help.
document.getElementById('contracts').style.display = 'none';
The above should do
You man consider using jQuery though. Makes your life simple
$('#contracts').hide();
That's all
Cheers
try and move the script to the bottom of the page. It's executing before the element is loaded. You could also put it in the "onload" function
window.onload = function(){
var myVal = 10;
if (myVal = 10) {
document.getElementById("contracts").style.visibility="hidden";
}
};
Instead of visibility, you should be looking at display property. Check the snippet below.
<HTML>
<head>
<title>Test</title>
</head>
<body>
<select id="contracts" name ="contracts" style="width:99%;height:50px"></select>
</body>
<script type="text/javascript">
var myVal = 10;
if (myVal = 10) {
document.getElementById("contracts").style.display="none";
}
</script
</html>

trying to change the counter color in javascript

i m trying to change color of counter when it reached th limit
but its not working . dont know why
im new to javascrit , i dont know about jquery , please asnwer in javascript.
here is my code work :
<!DOCTYPE html>
<html>
<head>
<script>
function counting(){
var count = document.getElementById('text1').value;
var grab = document.getElementById('text1');
var count1 = document.getElementById('p1');
count1.innerHTML = count.length;
if (grab.length > 10) {
count1.style.color="#0033bb";
};
}
</script>
</head>
<body>
<textarea id="text1" onkeyup="counting();"></textarea>
<p id="p1">0</p>
</body>
</html>
grab is element, instead you want its value
if (grab.value.length > 10) {
count1.style.color="red";
}
working fiddle:
http://jsfiddle.net/entw1e39/
As others are pointing out you can also use
if (count.length > 10) {
count1.style.color="red";
}
but then i would rewrite
var grab = document.getElementById('text1');
var count = grab.value;
It is a good practice. There is no need to call DOM two times, it is cost inefficient.
grab is the input element, and grab.length is always undefined.
You may use count.length instead of grab.length.

Dynamically Creating bootstrap-sliders with jquery or javascript

I'm trying this with no success. For reference, the bootstrap slider is here : http://seiyria.github.io/bootstrap-slider/.
I'm not a javascript expert, either, so this might be very simple. The bootstrap-slider site has many examples of how to configure the sliders the way you want them. I'm going to have many sliders generated depending on how many objects are pulled from a JSON file or some other data storing method. It could be 2 or it could be 20.
I created a javascript function called createSlider that I've attempted to pass all of the information required at the bootstrap-slider site. I'm not getting any errors in my Chrome debugging area, but nothing is happening. All of the appropriate client-side sources are loading.
function createSlider (orgId) {
slidersList = document.getElementById('slidersList');
element = slidersList.createElement("div");
var sliderElement = element.createElement('input');
var sliderUnique= orgId.concat("Slider");
var sliderUniqueVal = orgId.concat("SliderVal");
sliderElement.setAttribute('id', charityId);
sliderElement.setAttribute('data-slider-id', sliderUnique);
sliderElement.setAttribute('type', 'text');
sliderElement.setAttribute('data-slider-min', '0');
sliderElement.setAttribute('data-slider-max', '100');
sliderElement.setAttribute('data-slider-step', '1');
sliderElement.setAttribute('data-slider-value', '50');
var span = element.createElement('span');
span.setAttribute('style', 'padding-left:5px;');
span.innerHTML =' ';
var innerSpan = span.createElement('span');
innerSpan.setAttribute('id', sliderUniqueVal);
innerSpan.innerHTML = '50';
sliderElement.slider({tooltip: 'hide'});
sliderElement.on("slide", function(slideEvt) {
innerSpan.innerHTML = text(slideEvt.value);
});
}
The slider() function is from the external site, and runs fine if I explicitly call it like the examples state to. Anyone know what's going wrong? Is there a better way to do this? Any ideas would be appreciated.
Note, in plain JavaScript, you can only use document.createElement and then append to another HTML element. You cannot call createElement directly against another HTML element.
I changed some of what you wrote from plain old JavaScript into JQuery, and now seems to work:
P.S. Didn't know where charityId came from, so just added it as another parameter into the function.
$(function() {
createSlider('o1','c1');
createSlider('o2','c2');
createSlider('o3','c3');
});
function createSlider (orgId, charityId) {
var slidersList = $('#slidersList');
var element = $("<div></div>").appendTo(slidersList);
var sliderElement = $("<input/>").appendTo(element);
var sliderUnique= orgId.concat("Slider");
var sliderUniqueVal = orgId.concat("SliderVal");
sliderElement.attr('id', charityId);
sliderElement.attr('data-slider-id', sliderUnique);
sliderElement.attr('type', 'text');
sliderElement.attr('data-slider-min', '0');
sliderElement.attr('data-slider-max', '100');
sliderElement.attr('data-slider-step', '1');
sliderElement.attr('data-slider-value', '50');
var span = $('<span></span>').appendTo(element);
span.attr('style', 'padding-left:5px;');
span.html(' ');
var innerSpan = $('<span></span>').appendTo(span);
innerSpan.attr('id', sliderUniqueVal);
innerSpan.html('50');
sliderElement.slider({tooltip: 'hide'});
sliderElement.on("slide", function(slideEvt) {
innerSpan.text(slideEvt.value);
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
<script type='text/javascript' src="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="http://seiyria.github.io/bootstrap-slider/stylesheets/bootstrap-slider.css">
<script type='text/javascript' src="http://seiyria.github.io/bootstrap-slider/javascripts/bootstrap-slider.js"></script>
<div id="slidersList"></div>

Categories