JavaScript button Enable and Disable - javascript

Hello there so I'm making a remake of the popular game cookie clicker but I'm having some issues so here is what I need help with
So as you know in the game cookie clicker, they have power up buttons and those buttons disable them selfs when you do not have enough money to buy it
and that's what I need help with I want to be able to have the power-up buttons disabled and when I have enough money make them auto enable
so here I'll put some example code to sort of explain it a bit better
code:
if (cookies >= 10) {
document.getElementById("IdName").disabled = false;
}else {
document.getElementById("IdName").disabled = true;
}

Something like this?
function evalButton() {
var cookies = document.getElementById("cookies").value;
cookies = parseInt(cookies, 10);
console.log(cookies);
if (cookies >= 10) {
document.getElementById("IdName").disabled = false;
}else {
document.getElementById("IdName").disabled = true;
}
}
#IdName {
background: red;
}
#IdName:disabled {
background: grey;
}
<input id="cookies" onkeyup="evalButton()"/>
<button id="IdName">Press me</button>
Your code is working fine-- and cookies value can be derived in the function or passed as an argument. A bit of CSS can be used to give visual cues to the disabled state.

Related

Pop up window, or separate screen n Js

I am making a clicker game, it is very simple, and mostly just a learning process, for me to learn JavaScript. I have added a "Shop" button, attempting to have a separate screen, or a popup, to make a Shop place, where the player can shop for power-ups, using their "clicks" to purchase them, then they can close out the shop, and continue with their game.
This is what i tried:
I already had this variable set:
...
shopMenu = false;
...
This is everything else:
// Shop Button
if (mouse.dist(shop) < 40) {
shopColor = "firebrick";
shopMenu = true;
if (shopMenu == true) {
// This area is what I need help on, I don't know how to make a separate screen, to pop up, for a "shop".
}
You can have a shop div element in your html like
<div id="shop">
<p>Welcome to the shop</p>
</div>
and in your styling, have it hidden by default
#shop {
display: none;
}
Then back in your javascript,
if(shopMenu === true) {
const shopElement = document.getElementById('shop');
shopElement.style.display = 'block'
}

HTML "if" statement background toggle

I'm new to learning CSS/HTML and i've been working a bit on trying to recreate the windows 98 vibe. However, one thing I've had a lot of trouble with specifically is trying to recreate the "start" button with a simple toggle script.
You can see an example of the current script i'm using here; https://thealonic.tumblr.com/ most of the work is my own work with some scraps of css from the old theme I was using along with win98.css
I've looked around a bit and tried around 4-5 solutions with no luck over the course of a couple hours, but none seemed to be helping me making any progress so I just tried to use more bare bones solutions by just using if statements.
<head>
<style>
.start_button {
float: left; background-image: url(https://cdn.discordapp.com/attachments/630047188520665121/785903172115234846/unknown.png);
height: 22px; width: 54px; margin-left: 2px; margin-top: 2px; z-index: 3; background-repeat:no-repeat;}
</style>
</head>
<body class="win98>
<div class="start_button" id="start_button" onclick="startpress()"></div>
<script>
function startpress() {
if (document.getElementById("start_button").style.backgroundImage !== "url('https://cdn.discordapp.com/attachments/630047188520665121/785903300292902982/unknown.png')") {
document.getElementById("start_button").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/785903300292902982/unknown.png')" } else {
document.getElementById("start_button").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/785903172115234846/unknown.png')"}}
</script>
</body>
This "almost" gets the job done but, the trouble I'm having is that the button recognises the press, and then it says down, even with such a simple if statement like this. I've seen this solution work for pretty much the exact same usecase but I don't understand why this doesn't quite work. Is there just something about html scripts specifically I don't quite understand?
Anyway, thanks for any help I get in advance and sorry if this has been asked before, but a quick search didn't get anything like this specifically as I'm not entirely sure if the cause is just the way I'm addressing the background image.
You probably need a Eval or something like that in the if.
But i would go with something more simple
var startmode=true
If (startmode)
{
startmode=false
document.getElementById("start_button").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/785903300292902982/unknown.png')"
}
else
{
startmode=true
document.getElementById("start_button").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/785903172115234846/unknown.png')"
}
The problem in your code is that the condition inside the if statement doesn't change every time you click the button. You need some kind of toggle that changes at every click. You can try something like this:
const startButton = document.getElementById("start_button");
let startButtonOpen = false;
function startpress() {
startButtonOpen = !startButtonOpen;
if (startButtonOpen) {
startButton.style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/785903300292902982/unknown.png')";
} else {
startButton.style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/785903172115234846/unknown.png')";
}
}
Here's the solution to the problem i finally got around to solving.
So for the taskbar I have this, which just toggles between true and false alongside addressing the window titlebar and the taskbar.
function tumblrtoggle() { pyroButtonOpen = true;
if (tumblrButtonOpen == false) { inactiveall(); tumblrButtonOpen = true;
document.getElementById("post").style.zIndex = (currentno = currentno + 1); currentno = currentno + 1;
document.getElementById("postwindow").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/791328235451318342/title-bar_postheaderinactive.png')";
document.getElementById("taskapp1").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/789420847604564008/Taskbar_application1.png')";
} else if (pyroButtonOpen == true){ inactiveall(); tumblrButtonOpen = false;
document.getElementById("postwindow").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/791321110750298162/title-bar_postheader.png')";
document.getElementById("taskapp1").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/789416557692452884/Taskbar_application.png')";}}
And having this else where in the html so you don't have to keep calling "true" to each window if you have multiple.
function inactiveall() {
tumblrButtonOpen = true;
document.getElementById("postwindow").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/791328235451318342/title-bar_postheaderinactive.png')";
document.getElementById("taskapp1").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/789420847604564008/Taskbar_application1.png')";
}
Then to actually create the script for the window for when the window is clicked onto;
function tumblractive() { tumblrButtonOpen = false;
document.getElementById("post").style.zIndex = (currentno = currentno + 1); currentno = currentno + 1;
document.getElementById("postwindow").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/791321110750298162/title-bar_postheader.png')";
document.getElementById("taskapp1").style.backgroundImage = "url('https://cdn.discordapp.com/attachments/630047188520665121/789416557692452884/Taskbar_application.png')";
}
Example is used here; https://thealonic.tumblr.com/ (all the windows use the same scripts with different names and alterations for different functionability)

How can we stop the execution of javascript for a while until a decision is made?

I want to build my own popup box using div's (not the browser default). So when I display my own popup I want to stop the javascript execution until the user clicks a button on my own popup, same as the default confirmation popup in browsers. Is there a way to do this? If so how? I would like to avoid using jQuery.
You can't (and shouldn't) block JavaScript execution. It would be possible by introducing an endless while loop, but that would seriously degrade performance and also affect the handling of click events.
So, the best and probably only way to do this, is to use a callback that is called when you press a button. This does mean that you can't call this alternative confirm method in a synchronous way, though. Instead you can provide a callback that is executed when one of the buttons is pressed.
I hacked together an example. This is just made up on the fly, and only has some rudimentary styling. If it contains minor flaws, please forgive me.
/**
* The alternative confirmation function
*/
window.myConfirm = function(options) {
// Create the elements
var popup = document.createElement('div');
var box = document.createElement('div');
var ok = document.createElement('button');
var cancel = document.createElement('button');
// Style them
popup.className = 'lightbox';
box.className = 'dialog';
ok.className = 'button buttonOK';
cancel.className = 'button buttonCancel';
// Button texts
ok.innerText = 'OK';
cancel.innerText = 'Cancel';
// Click handlers.
ok.onclick = function(event) {
popup.parentNode.removeChild(popup);
options.onConfirm();
}
cancel.onclick = function(event) {
popup.parentNode.removeChild(popup);
options.onDecline();
};
// Clicking the box does nothing.
box.onclick = function(event){
event.stopPropagation();
};
// Clicking the popup equals cancel.
popup.onclick = cancel.onclick;
// Add all elements to the document.
popup.appendChild(box);
box.innerHTML = "<div><h2>" + options.title + "</h2>" + options.prompt + "</div>";
box.appendChild(ok);
box.appendChild(cancel);
// Finally show the box.
document.body.appendChild(popup);
};
/**
* The call
*/
myConfirm({
title: "Confirm",
prompt: "Are you sure?",
onConfirm: function() {
// The code that is executed when user presses OK.
alert('You confirmed');
},
onDecline: function() {
// Code executed on cancel, or when clicking next to the box.
alert('You declined');
}
});
.lightbox {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0,0,0,0.5);
text-align: center;
}
.dialog {
display: inline-block;
margin-top: 50px;
background-color: white;
padding: 50px;
}
.dialog div {
text-align: left;
}
There is no way of stopping the execution, get an input from the user and then continue from some point without using JavaScript popup boxes. You can build one on your own with html components and display it with buttons, provide call backs. You would need to block the window from user access, take the input and then unblock the window. You may use Javascript frameworks like jQuery to get a better styled, enhanced and optimized component. Here is piece of code demonstration:
JavaScript
function myCancelClick() {
hidePrompt();
alert("Cancel");
}
function myOkClick(){
hidePrompt();
alert("Ok");
}
function showPrompt() {
document.getElementById("promptPane").style.display = '';
document.getElementById("displayPane").style.display = 'none';
}
function hidePrompt() {
document.getElementById("promptPane").style.display = 'none';
document.getElementById("displayPane").style.display = '';
}
HTML body
<body>
<div id="displayPane">
<input type="button" onclick="showPrompt()" value="Show Prompt"/>
</div>
<div id="promptPane" style="display: none;">
<div id="myPrompt">what would you like to click?<input type="button" onclick='myCancelClick();' value="Cancel"/><input type="button" onclick='myOkClick();' value="Ok"/>
</div>
</div>
</body>
Fiddle
If you know, how much time you want to stop for; try using setTimeout() function of Javascript to produce a delay

How Can I Insert My Javascript Into My Drupal Site/Node

I'm trying to insert a cookie that is provided by a video host that will resume a video where the user left off. They have an example that obviously works. When trying to insert this into my Drupal site, the cookie won't work. The video just starts back at the beginning.
I have enabled "PHP input filter", as I read that I needed to do that for drupal to insert the script. Please see the code that is in my node below.
Can anyone help me figure out why this isn't working, how to get it to work, or a better way of doing this with Drupal?
Thank you,
<script type="text/javascript">
wistiaEmbed.ready( function() {
var all_cookies = document.cookie.split(';'), // gets the value of the cookies on the page
cookie_str = "resume_video=",
resume_cookie = does_resume_cookie_exist(all_cookies);
function does_resume_cookie_exist(cookie_arr) {
var i, curr_string, found;
for (i = 0; i < cookie_arr.length; i++) {
curr_string = cookie_arr[i];
if (curr_string.substring(0,5) === cookie_str.substring(0,5)) {
// we've found it!
found = curr_string;
break;
}
}
return found;
}
function set_cookie_time(t) {
document.cookie = cookie_str + t.toString(); // this takes the time (t) and sets the cookie with that time
}
if (resume_cookie) {
num = resume_cookie.split('=')[1];
start_time = parseInt(num);
wistiaEmbed.time(start_time).play(); // plays the video at the specific time defined in the cookie upon return to the page
} else {
set_cookie_time(0); // places a cookie on the visitor
wistiaEmbed.play(); // starts the video from the beginning
}
wistiaEmbed.bind("timechange", function(t) { // on timechange, reset cookie
set_cookie_time(t);
});
wistiaEmbed.bind("end", function() { // if person has watched the entire video, sets the video to beginning upon retun
set_cookie_time(0);
});
});
</script>
<div id="wistia_npcc5k96s9" class="wistia_embed" style="width:640px;height:508px;"> </div>
<script charset="ISO-8859-1" src="http://fast.wistia.com/assets/external/E-v1.js"> </script>
<script>
wistiaEmbed = Wistia.embed("npcc5k96s9");
</script>**strong text**
What version of drupal are you using? Does the code that you gave actually output in your request response?
There are several solutions to this (IMO).
If the code is showing up in the response, it could be some other javascript error that preventing your code from executing.
If that snippet of code is applicable to all nodes of that type you can use the node_view hook in order to inject your code on that node type, for example (I am assuming D7):
function mymodule_node_view($node, $view_mode)
{
if($node->type =='video_page')
{
drupal_add_js('resume_video.js'); // this js holds your code snippet
}
}
Here's a reference that could help you out
https://api.drupal.org/api/drupal/modules%21node%21node.api.php/function/hook_node_view/7
You can similarly inject that snippet of code at the theme layer using a theme hook, probably hook_preprocess https://api.drupal.org/api/drupal/modules!system!theme.api.php/function/hook_preprocess/7
Hope that helps.

jQuery Cookie Question

I've looked around a lot, and can't seem to find anything that's simple enough for me to do...
I've set up a web page that detects which browser is currently running, and if it's something other than Firefox 4.0, it displays a hidden div that gives a warning stating that the page is best viewed in Firefox 4.0 or greater. Within that div is a button that hides the div onclick.
I'm looking for a way to remember that this button has been clicked during a session, so that when a user clicks on my "home" page, they don't get the same message every time.
Current code:
<head>
<script src="js/browsercheck.js"></script>
<script type="text/javascript">
// external script "browsercheck.js" checks
// which browser/version is being used
// check browser and display message if != Firefox 4.0 or >
function checkBrowser() {
var browser = BrowserDetect.browser;
var version = BrowserDetect.version;
if (browser == "Firefox") {
if (version >= 4) {
// do nothing
}
} else {
document.getElementById("coverall").style.visibility="visible";
document.getElementById("browser").innerHTML = browser + " " + version;
}
}
// remove overlay if user commands
function removeCoverall() {
document.getElementById("coverall").style.visibility="hidden";
}
</script>
</head>
<body>
<div id="coverall" style="visibility:hidden;">
<p>I see you're using <span id="browser"></span>. Please use Firefox.</p>
<button type="button" onclick="removeCoverall()">I understand</button>
</div>
</body>
Using jQuery and the cookie plugin, you can do:
function removeCoverall() {
$.cookie("user_clicked_ok", "true");
document.getElementById("coverall").style.visibility="hidden";
}
$(window).ready(function() {
if ($.cookie("user_clicked_ok")=="true") {removeCoverall();}
});
More details at: http://www.electrictoolbox.com/jquery-cookies/
In the removeCoverall function you could set a cookie which indicates that the user closed the div and in checkBrowser function verify if the cookie is present before showing the div.
You seem to have the right idea, you need cookies! YUM!
JS
function removeCoverall() {
var date = new Date();
date.setTime(date.getTime()+(7*24*60*60*1000));// expires in one week
document.cookie = 'skipNotify=1;expires='+date.toGMTString()+'; path=/';
document.getElementById("coverall").style.visibility="hidden";
}
Now retrieving the cookie can be difficult in javascript, but you can use PHP!
PHP
function checkBrowser() {
<?php if(isset($_COOKIE['skipNotify']))echo'return;';?>
var browser = BrowserDetect.browser;
var version = BrowserDetect.version;
if (browser == "Firefox") {
if (version >= 4) {
// do nothing
}
} else {
document.getElementById("coverall").style.visibility="visible";
document.getElementById("browser").innerHTML = browser + " " + version;
}
}
The above code injects a return statement if the user has the cookie, so the call to the function won't do anything.
As mentioned in the other posts, I highly recommend you use jQuery for all your javascript needs. It's very popular, stable and useful! I only gave my answer as it does not use any third party solution.

Categories

Resources