Javascript - changing widths of images - javascript

I'm creating a tug of war website as a small project. My problem is that my javascript doesn't seem to want to work.
<script>
function randomTeam(){
var TeamV = Math.floor((Math.random() *2 ) + 1)
document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
return TeamV;
}
function changeWidth(TeamV){
var MetreLeftV = document.getElementById('MetreLeft');
var MetreRightV = document.getElementById('MetreRight');
if(TeamV == 1){
MetreLeftV.style.width += '10px';
MetreRightV.style.width -= '10px';
}
else if(TeamV == 2){
MetreRightV.style.width += '10px';
MetreLeftV.style.width -= '10px';
}
}
</script>
Basically, when the page is loaded the randomTeam function is called, and when the button is pressed, it increments the size of your teams side, and decrements the side of the enemy's team. The problem is, it doesn't work at all. Could anyone help me see where this is going wrong? Thank you in advance :')

You can not just add 10px to the width. Convert the width to a number, add 10, than add px to it.
MetreLeftV.style.width = (parseFloat(MetreLeftV.style.width) + 10) + "px"
Do the same for the others and you will need a check for negative numbers.
function randomTeam() {
var TeamV = Math.floor((Math.random() * 2) + 1)
document.getElementById("TeamHeader").innerHTML = "Team: " + TeamV;
return TeamV;
}
function changeWidth(TeamV) {
var MetreLeftV = document.getElementById('MetreLeft');
var MetreRightV = document.getElementById('MetreRight');
console.log(parseFloat(MetreLeftV.style.width) + 10 + 'px')
if (TeamV == 1) {
MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) + 10 + 'px';
MetreRightV.style.width = parseFloat(MetreRightV.style.width) - 10 + 'px';
} else if (TeamV == 2) {
MetreLeftV.style.width = parseFloat(MetreLeftV.style.width) - 10 + 'px';
MetreRightV.style.width = parseFloat(MetreRightV.style.width) + 10 + 'px'
}
}
window.setInterval( function () {
var move = randomTeam();
changeWidth(move);
}, 1000);
#MetreLeft {
background-color: red
}
#MetreRight {
background-color: yellow
}
<div id="TeamHeader"></div>
<div id="MetreLeft" style="width:200px">Left</div>
<div id="MetreRight" style="width:200px">Right</div>

Related

JavaScript button not running function or disappearing after clicked

EDIT: the issue was a typo, this should have been caught and is not a good question. Sorry about that
So I've been working on making one of my own projects in JS, and it involves lots of buttons. I have one button (The one with the ID of "firstbuildmulti1") which should run the function "build1multi1" But I don't think it is doing that. I've looked over it multiple times and I'm not sure why it won't work. Any help is appreciated! (Side note: the button only appears after you click the third building button, this is intentional). EDIT: I ran the code on here and it said:
{
"message": "Uncaught ReferenceError: b1m1cost is not defined",
"filename": "https://stacksnippets.net/js",
"lineno": 183,
"colno": 17
}
My code is:
//declare variables for points, multiplier, buy upgrade, b1 2 and 3 cost and count, make point updater
var points = 9999;
var pointMulti = 1;
var buyupgrade = 0;
var b1cost = 200;
var b1count = 0;
var b2cost = 1000;
var b2count = 0;
var b3cost = 2000;
var b3count = 0;
var b1m1cost = 1500;
var currentpoints = setInterval(pointupdate, 500);
//clicking on main button to add points
function addPoints() {
points += pointMulti;
var pointsArea = document.getElementById("pointdisplay");
pointsArea.innerHTML = "You have " + Math.round(points) + " points!";
if(points >= 100 && buyupgrade == 0) {
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "inline";
console.log();
}
}
//make logic for doubling addpoints
function firstx2() {
if (buyupgrade == 0) {
pointMulti *= 2;
buyupgrade++;
points -= 100;
var multiplierArea = document.getElementById("multidisplay");
multiplierArea.innerHTML = "Your multiplier is: " + pointMulti;
var multiply_button = document.getElementById("btn_multiply");
multiply_button.style.display = "none";
//logic for displaying first building upgrade
if (buyupgrade == 1) {
var firstbuild = document.getElementById("firstbuild");
firstbuild.style.display = "inline";
firstbuild.innerText = "Building 1. Cost " + b1cost;
var show2ndx2 = document.getElementById("secondx2");
multiply2.style.display = "inline";
}
}
}
//displays total points
function pointupdate() {
document.getElementById("pointdisplay").innerHTML = "You have " + Math.round(points) + " points!";
}
//what happens when you click first building button
function build1() {
if (points >= b1cost) {
points -= b1cost;
b1count++;
b1cost *= 1.10;
var b1multi = 1;
var b1pps = b1count * b1multi;
document.getElementById("b1").innerHTML = "You have " + b1count + " of building 1! Making " + b1pps + " points per second."
firstbuild.innerText = "Building 1. Cost " + Math.round(b1cost);
var build1add = setInterval(build1points, 1000);
//display second building
var secondbuild = document.getElementById("secondbuild");
secondbuild.style.display = "inline";
secondbuild.innerText = "Building 2. Cost " + b2cost;
}
}
//what happens when you click second building button
function build2() {
if (points >= b2cost) {
points -= b2cost;
b2count++;
b2cost *= 1.10;
var b2multi = 1;
var b2pps = (b2count * 4) * b2multi;
document.getElementById("b2").innerHTML = "You have " + b2count + " of building 2! Making " + b2pps + " points per second."
secondbuild.innerText = "Building 2. Cost " + Math.round(b2cost);
var build2add = setInterval(build2points, 1000);
//display third building
var thirdbuild = document.getElementById("thirdbuild");
thirdbuild.style.display = "inline";
thirdbuild.innerText = "Building 3. Cost " + b3cost;
}
}
//what happens when you click third building button
function build3() {
if (points >= b3cost) {
points -= b3cost;
b3count++;
b3cost *= 1.10;
var b3multi = 1;
var b3pps = (b3count * 10) * b3multi;
document.getElementById("b3").innerHTML = "You have " + b3count + " of building 3! Making " + b3pps + " points per second."
thirdbuild.innerText = "Building 3. Cost " + Math.round(b3cost);
var build3add = setInterval(build3points, 1000);
//first building first multiplier
var firstbuildmulti1 = document.getElementById("firstbuildmulti1");
firstbuildmulti1.style.display = "inline";
firstbuildmulti1.innerText = "Building 1 x2 multiplier. Cost: " + b1m1cost + "."
}
}
//add points for build1
function build1points() {
points += 1;
}
//add points for build2
function build2points() {
points += 4;
}
//add points for build3
function build3points() {
points += 10;
}
//second x2, display multiplier
function secondx2() {
if (buyupgrade == 1 && points >= 1000) {
pointMulti *= 2;
points -= 1000;
document.getElementById("multidisplay").innerHTML = "Your multiplier is: " + pointMulti;
multiply2.style.display = "none";
}
}
function build1multi1() {
if (points >= b1m1cost) {
points -= b1m1cost;
b1multi *= 2;
var build1multi1 = document.getElementById("build1multi1");
build1multi1.style.display = "none";
}
}
<p>Click to get started!</p>
<!--Link to all CSS files -->
<link rel="stylesheet" href="buttons.css">
<link rel="stylesheet" href="displayscores.css">
<link rel="stylesheet" href="layout.css">
<!-- make all buttons -->
<button id="addpoints" onclick="addPoints()" background-color:red>Add points</button>
<button id="firstbuild" onclick="build1()" style="display:none;">Building 1. Cost x</button>
<button id="secondbuild" onclick="build2()" style="display:none;">Building 2. Cost x</button>
<button id="thirdbuild" onclick="build3()" style="display:none;">Building 3. Cost x</button>
<br>
<p><b>Upgrades:</b></p>
<button id="btn_multiply" onclick="firstx2()" style="display:none;">x2 Multiplier. Cost: 100</button>
<button id="multiply2" onclick="secondx2()" style="display:none;">x2 Multiplier. Cost: 1000</button>
<button id="firstbuildmulti1" onclick="build1multi1()" style="display:none;">Building 1 x2 multiplier. Cost x</button>
<!-- make a div around all paragraphs displaying stats and display them -->
<div class="displayscores">
<p id="pointdisplay"></p>
<p id="multidisplay"></p>
<p id="b1"></p>
<p id="b2"></p>
<p id="b3"></p>
</div>
First things first, as discussed in the comments, anytime you're stuck with the code, you can try using console.log() (If you're new to it, research a bit on using the Console for debugging)
function build1multi1() {
console.log("Entered function"); //If this is printed in console, that means the function is called
if (points >= b1m1cost) {
console.log("Entered condition"); //If this is not printed in console, it means condition points >= b1m1cost fails.
// console.log(b1m1cost); // You can check b1m1cost value in the console
// console.log(points); // You can check points value in the console
points -= b1m1cost;
b1multi *= 2;
var build1multi1 = document.getElementById("build1multi1");
build1multi1.style.display = "none";
}
}
Problem 1 : b1m1cost is not defined
b1m1cost is not defined in the global scope. It is only declared in one of the functions. Hence, the condition inside build1multi1() must be failing.
Problem 2 : Can't read property style of null (Doesn't hide the button)
This is happening inside the build1multi1() function.
Which means var build1multi1 inside that function is null.
Which means document.getElementById("build1multi1"); is unable to find any element with id build1multi1.
If you want to hide the button then the id should be firstbuildmulti1 which is the id for the button. So, change it to document.getElementById("firstbuildmulti1");

use id from another js file

Ok I have some legacy JS that get results from a users test, i have this JS file refrenced in my code so i can use the ID results-percentile-2in my HTML as so
your score
<span id="results-percentile-2"></span>%
However I have a piece of javascript I would like to call the ID in instead of in the HTML
<script>
function move() {
var elem = document.getElementById("myBar");
var width = 0;
var id = setInterval(frame, 50);
function frame() {
if (width >= 40) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
document.getElementById("demo").innerHTML = width * 1 + '%';
}
}
}
</script>
I would like to use results-percentile-2 to set the width, I have tried
<script>
function move() {
var elem = document.getElementById("myBar");
var width = 0;
var id = setInterval(frame, 50);
function frame() {
if (width >= document.getElementById("results-percentile-2")) {
clearInterval(id);
} else {
width++;
elem.style.width = width + '%';
document.getElementById("demo").innerHTML = width * 1 + '%';
}
}
}
</script>
but is this the correct way of doing it as its not working, or should i point to the correct js file the id is in for example
if (width >= myjavascript.js.getElementById("results-percentile-2"))
UPDATE
This is the Legacy code im geting the js from
$("#next-button")
.click(function () {
a.eventHub.publish("ui/nextclick")
}), this.showView("test")
}, UI.prototype.updatePercentile = function (a) {
if (this.isStandalone || -1 == a.percentile) $("#results-percentages")
.hide();
else {
$("#results-percentages")
.show(), $("#results-percentile-1")
.html(a.percentile), $("#results-suffix")
.html(a.suffix), $("#results-suffix-2")
.html(a.suffix), 1 === a.timesTaken ? ($("#results-timestaken")
.html(a.timesTaken + " time"), $("#results-percentile-2")
.html("100")) : ($("#results-timestaken")
.html(a.timesTaken + " times"), $("#results-percentile-2")
.html(a.percentile));
var b = 0;
$("#percentile-scale .scale-item")
.each(function () {
b += $(this)
.outerWidth()
}), $("#percentile-scale .scale-indicator")
.css("width", b * a.percentile / 100 + "%"),
$(".scale-marker")
.css("left", b * a.percentile / 100 + "%")
}
With this statement
if (width >= document.getElementById("results-percentile-2"))
you are comparing a value with an object (a [SPAN]).
You must change your statement to
if (width >= document.getElementById("results-percentile-2").innerHTML)

Javascript how to set interval time to stop scrolling

This is the demo in jsfiddle, demo
What I want is let the scrolled items('one ', 'two', 'three', '4', '5', '6', '7') automatically scroll up like the demo showed, and stop 2 sec when it's in the middle position. But in my demo, it will shack for a while after stopping in the middle position.
Here is the place in my demo code for setting position.
if ((x == 0) || (x % 35== 0)) {
setTimeout(function () {
i.top = x + 'px';
}, 1000);
} else {
i.top = x + 'px';
}
Any one can help me? Thanks!
UPDATE:
The reason why I set 35 is because I found that the scrolled items are approximately in the middle position when it equals to 0, -35,-70,-105,.... But when I console all x, I found that the value of x is between (31, -251). Do you know how to find the exact position when each items are in the middle of position? Thanks!
i modified your code a bit,
i set a variable "k" that the interval is assigned to and i clear the interval on stop and start it again after the timeout
looks good for me -> http://jsfiddle.net/ato0mf7u/3/
no funny shakin anymore ;-D
window.onload = addScrollers;
var i = 1;
var arr = ['one ', 'two', 'three', '4', '5', '6', '7'];
var mid;
var k;
function addScrollers() {
var txt = arr[0];
while (i < arr.length) {
txt += '<p>' + arr[i] + '</p>';
i++;
}
startScroll('myscroller', txt);
}
var speed = 10; // scroll speed (bigger = faster)
var dR = false; // reverse direction
var step = 1;
function objWidth(obj) {
if (obj.offsetWidth) return obj.offsetWidth;
if (obj.clip) return obj.clip.width;
return 0;
}
function objHeight(obj) {
if (obj.offsetHeight) return obj.offsetHeight;
if (obj.clip) return obj.clip.height;
return 0;
}
function scrF(i, sH, eH) {
var x = parseInt(i.top) + (dR ? step : -step);
if (dR && x > sH) {
x = -eH;
} else if (x < 1 - eH) {
x = sH;
}
//when x is the times of 35, the positio is in middle
if ((x == 0) || (x % 35== 0)) {
clearInterval(k);
setTimeout(function () {
i.top = x + 'px';
k = setInterval(function () {
scrF(i, sH, eH);
}, 1000 / speed);
}, 1000);
}
else {
i.top = x + 'px';
}
return x;
}
function startScroll(sN, txt) {
var scr = document.getElementById(sN);
var sW = objWidth(scr);
var sH = objHeight(scr);
scr.innerHTML = '<div id="' + sN + 'in" style="position:absolute; left:3px; width:' + sW + ';">' + txt + '<\/div>';
var sTxt = document.getElementById(sN + 'in');
var eH = objHeight(sTxt);
mid = (eH - sH) / 2;
sTxt.style.top = (dR ? -eH : sH) + 'px';
sTxt.style.clip = 'rect(0,' + sW + 'px,' + eH + 'px,0)';
k = setInterval(function () {
scrF(sTxt.style, sH, eH);
}, 1000 / speed);
}

How to "echo" or show pictures from Javascript

I'm trying to use the below code to reflect different pictures of the moon into an HTML doc. Of course i've added the Jquery and Javascript tags.
I've been looking at this for hours and trying different things but I can't find out what to put into HTML code that will actually show or echo the pictures.
What should I put into the "moonImage.src = "pix/moon" + truncPhase + ".png";" part of the code? I don't understand how to essentially echo the photos. Help please?:
// Image max size
var IMAGE_MAX_SIZE = 196;
// Records whether or not the gadget is expanded
var poppedOut = false;
function onOpen() {
// Check once every 30 minutes
view.setInterval(onTimer, 30 * 60 * 1000);
// Initialize the gadget
onTimer();
}
// Called when the timer goes off
function onTimer() {
// Compute the moon phase each time timer is called
var cal = new Date();
// Base the computation off of UTC time, to the nearest hour
var phase = computeMoonPhase(cal.getUTCFullYear(),
cal.getUTCMonth() + 1,
cal.getUTCDate(),
cal.getUTCHours());
var truncPhase = Math.floor(phase) % 30;
// Find the text description of the current phase
var desc;
if (truncPhase === 0) {
desc = STRING_MOON_DESC_NEW;
} else if (truncPhase == 7) {
desc = STRING_MOON_DESC_FIRST_QUARTER;
} else if (truncPhase == 15) {
desc = STRING_MOON_DESC_FULL;
} else if (truncPhase == 23) {
desc = STRING_MOON_DESC_THIRD_QUARTER;
} else if (truncPhase > 0 && phase < 7) {
desc = STRING_MOON_DESC_WAXING_CRESCENT;
} else if (truncPhase > 7 && phase < 15) {
desc = STRING_MOON_DESC_WAXING_GIBBOUS;
} else if (truncPhase > 15 && phase < 23) {
desc = STRING_MOON_DESC_WANING_GIBBOUS;
} else {
desc = STRING_MOON_DESC_WANING_CRESCENT;
}
// Set the image and text component appropriately
moonImage.src = "pix/moon" + truncPhase + ".png";
moonImage.tooltip = (Math.floor(phase * 100) / 100) + " " + STRING_DAYS_OLD;
phaseAge.innerText = STRING_MOON_AGE_PREFIX + " " + moonImage.tooltip +
"\n" +
desc;
}
// Called when view is resized (recompute constituent basicElement sizes and
// locations)
function resizeView() {
setDimensions(event.width, event.height);
}
// Open the browser whenever a user double clicks (expanded or collapsed)
function onDblClick() {
var obj = new ActiveXObject("Shell.Application");
obj.Open("http://stardate.org/nightsky/moon/");
}
// Show date age in title, when gadget is minimized
function onMinimize() {
view.caption = STRING_MOON_SHORT + " - " + moonImage.tooltip;
}
// Only show the textual part (details) when popped out
function onPopout() {
poppedOut = true;
phaseAge.visible = true;
}
// Hide the textual part in restored mode, show regular title, and reset
// dimensions
function onRestore() {
view.caption = GADGET_NAME;
phaseAge.visible = false;
//moonImage.enabled = true;
poppedOut = false;
setDimensions(view.width, view.height);
}
// Called whenever the sizes and/or locations of basicElements need to change
function setDimensions(width, height) {
// Image is square, constrained by smallest dimension
var sz = Math.min(width, height);
// Make the image almost as large as the sz
moonImage.width = Math.min(IMAGE_MAX_SIZE, sz * 0.9);
moonImage.height = Math.min(IMAGE_MAX_SIZE, sz * 0.9);
if (poppedOut) {
// Align image on left, and set text location
moonImage.x = 0;
phaseAge.x = moonImage.width + 5;
phaseAge.y = (height - phaseAge.height) / 2;
} else {
// Center image horizontally
moonImage.x = (width - moonImage.width) * 0.5;
}
// Always center image vertically
moonImage.y = (height - moonImage.height) * 0.5;
}
// Compute the moon phase.
// Code is based upon Bradley E. Schaefer''s well-known moon phase algorithm.
function computeMoonPhase(year, month, day, hours) {
var MOON_PHASE_LENGTH = 29.530588853;
// Convert the year into the format expected by the algorithm
var transformedYear = year - Math.floor((12 - month) / 10);
// Convert the month into the format expected by the algorithm
var transformedMonth = month + 9;
if (transformedMonth >= 12) {
transformedMonth = transformedMonth - 12;
}
// Logic to compute moon phase as a fraction between 0 and 1
var term1 = Math.floor(365.25 * (transformedYear + 4712));
var term2 = Math.floor(30.6 * transformedMonth + 0.5);
var term3 = Math.floor(Math.floor((transformedYear / 100) + 49) * 0.75) - 38;
var intermediate = term1 + term2 + (day + (hours - 1) / 24) + 59;
if (intermediate > 2299160) {
intermediate = intermediate - term3;
}
var normalizedPhase = (intermediate - 2451550.1) / MOON_PHASE_LENGTH;
normalizedPhase = normalizedPhase - Math.floor(normalizedPhase);
if (normalizedPhase < 0) {
normalizedPhase = normalizedPhase + 1;
}
// Return the result as a value between 0 and MOON_PHASE_LENGTH
return normalizedPhase * MOON_PHASE_LENGTH;
}
HTML:
<html>
<head><title>Kendrick Moon</title>
<script src="ajax.googleapis.com/ajax/libs/jquery/1.8.3/ (etc.)
<script src="code.jquery.com/ui/1.9.2/jquery-ui.js"></script>;
<script src="main.js" type="text/javascript"></script>
<head>
<body>
<div><img src=""/> </div>
</body>
</html>
ok, well thats then easy.
first of all, you might want to check out jquery. with jquery it would be something like this.
<img src="" id="my_image" />
in javascript then (with jquery)
// the `myLinkToImage` is hopefully the variable of your path
$("#my_image").attr("src", myLinkToImage);
as you can see I´m using #. That is a typical jQuery Selector. You might check out more of them here
in javascript without jquery
document.getElementById("my_image").src = myLinkToImage;

DHTML - Show picture for limited time

im try to use DHTML in order to make animation for 3-5 sec( the anumation supose to start from the left to the right...).
any idea how to do tthat???
//this one will set the the pictue on the right side of the screen
function setUpPicture() {
subRunnerOBJ = new Object();
subRunnerOBJ.topPos = 100;
subRunnerOBJ.leftPos = 0;
subRunnerOBJ.velX = 400;
subRunnerOBJ.velY = 0;
subRunnerOBJ.score = 0;
hide1.style.visibility = "visible";
hide1.style.left = subRunnerOBJ.leftPos + "px";
hide1.style.top = subRunnerOBJ.topPos + "px";
hide1.style.position = "absolute";
//once we place the location of the sub , we will Call to new function that will move it
startMovePicture();
}
function startMovePicture() {
dt = 50; // in miliseconds
h = setInterval("moveObj(subRunnerOBJ)", dt);
}
function moveObj(someObj) {
counter = 0;
while (counter < 30000) {
subRunnerOBJ.leftPos = subRunnerOBJ.leftPos + subRunnerOBJ.velX * dt / 1000;
subRunnerOBJ.topPos = subRunnerOBJ.topPos + subRunnerOBJ.velY * dt / 1000;
hide1.style.left = subRunnerOBJ.leftPos + "px";
hide1.style.top = subRunnerOBJ.topPos + "px";
counter = counter + 50;
if (counter == 3000) {
stopRunning();
}
}
}
function stopRunning() {
clearInterval(h);
hide1.style.visibility = "hidden";
}
with this function i can see the picture for less than a sec...
how can i set the time here??
Replace the milliseconds value with a number equal to the desired number of seconds, which would be 5000 for five seconds. Remove the while loop inside of moveObj and replace it by adding clearInterval(h) and hide1.style.visibility = "hidden"; as the last statement inside that block.

Categories