Data-percent works only sometimes javascript - javascript

(Sorry for bad english) Hi, I'm trying to make a JavaScript app which is basically a music player and I can't figure out why one thing is not working. There's a chart that displays the music percentage (here's a screenshot) made with jQuery CDN and a GitHub source. The percentage resets at the beginning of the song (and this works) because of songTime.dataset.percent = 0;.
Then, there's the songTime.dataset.percent = sliderPosition; in a function that calculate at what point are you in the song
function chartUpdate() {
let sliderPosition = 0;
if (currentSong.duration != NaN) {
sliderPosition = Math.round(currentSong.currentTime * (100 / currentSong.duration));
songTime.dataset.percent = sliderPosition;
}}
It is in an if statement which is in a function, but this doesn't work (it's not because of the variable, I've checked it).
I've tested it several times, and the only difference between the two lines is that the one that doesn't work is in an if statement (as I already said, which is in a function).
I know it can be difficult to understand me because there isn't any code (I tried to add it, but in stackoverflow it doesn't work, I don't know why), but if you need (I don't know if it can be helpful) I hosted the non-working website here. Summing up, my problem is that the data-percent works only sometimes.

Your if statement contains invalid syntax. Replace
if (currentSong.duration != NaN)
with
if ( ! isNaN(currentSong.duration) )

Related

Possible to have two conditions for an IF statement in javascript?

Alright so I am currently making a PBBG based game. However, I have been having trouble with my function for a button click and two conditions in my if statement. I am actually not positive if this is at all possible, I searched everywhere I could think of but nothing gave me a definitive answer for getting this to work.
Basically, what I am trying to achieve, is that when a player presses the 'Attack' button, the player then receives the amount of experience points and gold they get from defeating that monster. Then, after that function runs, I am setting a delay of 6 seconds to where they can't press the button to attack again until the 6 seconds have passed.
I did get the function and onClick to work where when they win the fight, the game awards them the experience and gold from the kill. That all worked great and I made sure that was all working BEFORE I started adding in the time delay function and all.
Here is my code for the function with the time delay I am trying to add: Code
(Won't allow me to embed pictures yet so a link will have to do for now) and I am using just an HTML button with the onClick value set to SingleAttack(). The code with the problem appears to be in this part...
if (attackReady) || (currentExp >= NeededExp) {...}
What I have done here is I am holding a boolean, named attackReady and setting it to 'true'. When the player presses the Attack button, it then changes the 'true' value to 'false' and then adds a setTimeout() and period in miliseconds for delay. It then sets attackReady back to true and puts a 6 second time delay before the function can be called again.
You'll notice there is an if and an else if in my function. The if code runs only when a players current experience points are greater than or equal to the needed experience points. I think my problem is coming from having two conditions in the if statement. I am not entirely sure if that is possible, I have looked everywhere to find an answer and nothing for javascript specifically. I know C# allows it, does javascript allow it and if so, did I do it right or have I done it wrong?
When the Attack button is clicked and the function is called, it does nothing at all. Any insights?
As #Thomas noted, the entire test needs to also be enclosed in braces. You currently have:
if (attackReady) || (currentExp >= NeededExp) {...}
and what you want is either:
if ( (attackReady) || (currentExp >= NeededExp) ) {...}
or more simply:
if (attackReady || currentExp >= NeededExp) {...}
One more thing:
From your description, it might be the case that you want both tests to be true to execute that block of code. If that is the case you want to use an AND with && rather than the || OR test. OR is true if either the left or the right hand side is true.

Simple Collision Detection in Javascript / Jquery?

I am working on a portion of a project that I am trying to detect when certain divs hit each other. In the code that I made, that doesn't work, I basically say take the first div's left amount, compare it to the other div's left amount, if they are within a certain amount it triggers an alert. If I get that much to work I am going to implant a way to say that if the distance between the two divs is 0 then it will run a certain function. I am afraid the scope of this project is too big for me, even though I am basically at the last part, because I have spent hours researching a simple way to add collision detection, but everything I find looks like rocket science to me, that is why I tried to create my own way below. So in summary, what I want to know is why my collision detection code doesn't work, how I can make it work if possible, and if not possible what is the next best option that I should use.
//Collision
function collision(){
var tri = $('#triangle');
var enemyPos = $('.object1').css('left');
var minHit = enemyPos - 32.5;
var maxHit = enemyPos + 32.5;
var triLoc = tri.css('left');
if(triLoc > minHit && triLoc < maxHit){
alert('hit');
}
}
collision();
}
}
full code: https://jsfiddle.net/kc59vzpy/
If the code you have above is definitely where the problem is, then you need to look at the enemyPos variable. Getting the left position also adds px, so enemyPos is 100px or something like that. When you add 32.5, you get 100px32.5 and when you subtract you get NaN, neither of which you want.
Before you add or subtract, use enemyPos = parseInt($('.object1').css('left')); to turn it into an actual number.

wheelnav.js bouncing effect

Working on a pie menu using wheelnav.js. Everything is going well thus far, but for the life of me I do not seem to find anywhere in the wheelnav.js documentation on how to suppress the bouncing effect when you make a menu choice.
For an example of this effect, please look at http://pmg.softwaretailoring.net/ , turn on the 'rotate' switch and click a number in the pie menu. The selected choice rotates around to the focus point (default top) and bounces to a stop.
The original examples from http://wheelnavjs.softwaretailoring.net/examples.html I thought would be helpful as the first example on that page has a pie menu that does not bounce, but they've obfuscated and minified the underlying examples javascript file.
Any hints or tips on where to look for more extensive documentation or detailed examples would be greatly appreciated.
UPDATE: found a reference to a wheel object in their website code that uses the animatetime property. Setting that to a low number, like 200, causes the wheel to spin faster but not bounce. Not a perfect solution, as I might want the spinning to be slower, but will suffice until I learn of a better method.
Try using something like this:
wheel = new wheelnav('wheelDiv');
wheel.animatetime = 1000;
wheel.animateeffect = 'linear';
I believe the linear setting is the specific property you are looking for.
This can be found on this page of the documentation
I have used wheelnav.js and also contact his auther for my problems, and he has given proper answer to me about my problem but you can not find proper documentation for this jquery, you can also ask him (mail him) for your problem if needed
you can use below code
indexWheel.animatetime = 2000; // by this you can set faster/slower speed
strong text
window.onload = function () {
var values = ['1','2','3','4'];
var percent = [51,11,30,8];
var tool = ["1234 (40.10%) \n Companies (9)","1234 (40.10%) \n Companies (9)","1234 (40.10%) \n Companies (9)","1234 (40.10%) \n Companies (9)"];
var indexWheel = new wheelnav("indexDiv");
indexWheel.animatetime = 2000;
indexWheel.navItemsContinuous = true;
indexWheel.navAngle = 0;
indexWheel.wheelRadius = indexWheel.wheelRadius * 0.9;
indexWheel.slicePathFunction = slicePath().PieSlice;
indexWheel.sliceSelectedTransformFunction = sliceTransform().MoveMiddleTransform;
indexWheel.colors = colorpalette.goldenyellow;
indexWheel.initWheel(values);
indexWheel.createWheel(values);
indexWheel.setTooltips(tool);
};
Additional info for animateeffect.
There is a link for available effects on this page. Press 'animate' button and click on 'easing type' link.
P.S. I know the lack of in-depth documentation which should contain reference for all properties. It's on my todo list, but this is a side project, pls be patient. ;) Thanks for your feedbacks!

Whack-A-Mole game with huge bug! Can I get some help fixing it?

I am writing a Whack-A-Mole game for class using HTML5, CSS3 and JavaScript. I have run into a very interesting bug where, at seemingly random intervals, my moles with stop changing their "onBoard" variables and, as a result, will stop being assigned to the board. Something similar has also happened with the holes, but not as often in my testing. All of this is completely independent of user interaction.
You guys and gals are my absolute last hope before I scrap the project and start completely from scratch. This has frustrated me to no end. Here is the Codepen and my github if you prefer to have the images.
Since Codepen links apparently require accompanying code, here is the function where I believe the problem is occuring.
// Run the game
function run() {
var interval = (Math.floor(Math.random() * 7) * 1000);
if(firstRound) {
renderHole(mole(), hole(), lifeSpan());
firstRound = false;
}
setTimeout(function() {
renderHole(mole(), hole(), lifeSpan());
run();
}, interval);
}
What I believe is happening is this. The function runs at random intervals, between 0-6 seconds. If the function runs too quickly, the data that is passed to my renderHole() function gets overwritten with the new data, thus causing the previous hole and mole to never be taken off the board (variable wise at least).
EDIT: It turns out that my issue came from my not having returns on my recursive function calls. Having come from a different language, I was not aware that, in JavaScript, functions return "undefined" if nothing else is indicated. I am, however, marking GameAlchemist's answer as the correct one due to the fact that my original code was convoluted and confusing, as well as redundant in places. Thank you all for your help!
You have done here and there in your code some design mistakes that, one after another, makes the code hard to read and follow, and quite impossible to debug.
the mole() function might return a mole... or not... or create a timeout to call itself later.. what will be done with the result when mole calls itself again ? nothing, so it will just be marked as onBoard never to be seen again.
--->>> Have a clear definition and a single responsibility for mole(): for instance 'returns an available non-displayed mole character or null'. And that's all, no count, no marking of the objects, just KISS (Keep It Simple S...) : it should always return a value and never trigger a timeout.
Quite the same goes for hole() : return a free hole or null, no marking, no timeout set.
render should be simplified : get a mole, get a hole, if either couldn't be found bye bye. If a mole+hole was found, just setup the new mole/hole couple + event handler (in a separate function). Your main run function will ensure to try again and again to spawn moles.

jQuery Color Cycle on a href links (Maximum call stack size exceeded and Firefox Issues.)

I'm attempting to make a page that will animate the a href links through a table of colors nice and smoothly. I currently have 2 problems with the code that I'm using experiencing a whole mix of problems relating to bad code (please note that JavaScript and jQuery I'm pretty damn weak at). I'm hoping that some Guru can spend 2mins and let me know what the problem or supply a better solution. (thanks in advance.).
Problems Encountered:
Uncaught RangeError: Maximum call stack size exceeded
Firefox is not smooth while Chrome is (Firefox just changes color).
Some hues are too dark
Performance seems an issue, maybe this is because of the Maximum stack size error
Libraries:
jQuery.v1.10.2.min.js
jQuery.color-2.1.0.js
Code:
jQuery(document).ready(function() {
spectrum();
function spectrum(){
var hue = 'rgb(' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ',' + (Math.floor(Math.random() * 256)) + ')';
jQuery('body a').animate( { color: hue }, 2000);
spectrum();
}
});
What I need:
Basically all I need is a script that will animate all links on the page from one color to another every 2seconds or more... smoothly. Ideally, I'll like to be able to select 6 or more colors that I know that work but due to my limited knowledge in JavaScript I don't know where to begin.
JSFiddle of the Code in Action
I've made a jsfiddle to hopefully save anyone time or just check what the current output looks like: http://jsfiddle.net/ebZ3x/
Yeah, you're recursively calling indefinitely which will quickly run you out of stack space. What you want instead is for the browser to regularly call your color changing function. We'll use window.setInterval() to accomplish that.
Then we'll also create an array of the six colors you want and we'll just randomly index into it. To add more colors just add them to the array.
jQuery(document).ready(function() {
function spectrum(){
var colors = [
'rgb(256,0,0)', //red
'rgb(0,256,0)', //green
'rgb(0,0,256)', //blue
'rgb(256,256,0)', //orange
'rgb(256,0,256)', //magenta
'rgb(0,256,256)']; //cyan
var hue = colors[(Math.floor(Math.random() * colors.length))];
jQuery('body a').animate( { color: hue }, 2000);
}
var intervalId = window.setInterval(spectrum, 2000);
});
I've been working on your question since you posted it yesterday, and I thought I would give it a shot so I might learn a little about setTimeout. And boy, have I learned - about the complexity of such a "simple" command. It's probably the most difficult I've encountered in javascript.
So I present my "answer" just as something to be viewed, with JoeClacks' answer obviously superior.
This FIDDLE shows the initiation of the timer (runmytimer) after loading the DOM. It changes the background color of two divs randomly. I've let it run for over an hour and it seems not to crash.
I added the "extra" stuff to make sure other things on the page don't interfere with the timer. So when you type into an input box, the timer continues. When you click the "save" button (I just moved the input text to another div) the timer continues.
Here is the relevant JS
var randomcolors = ['#FF00FF','#00FFFF','#FFFF00','#0000FF','#00FF00','#FF0000','#000000','#C0C0C0','#C0C1C1','#CFCHCH','#CCFFCC'];
var timer;
//var timer_is_on = 0;
runmytimer();
$('#saveme').click(function(){
var moveme = $('#getme').val();
$('.movemehere').html(moveme);
});
function runmytimer()
{
t = setTimeout( function(){ runmytimer() }, 1000 );
random = Math.floor(Math.random() * (11 - 0 + 1)) + 0;
$('.putmehere1').css('background-color', randomcolors[random]);
$('.putmehere2').css('background-color', randomcolors[random+1]);
}
For other noobs such as myself who are reading this, I've learned a few things that aren't clearly stated in any documentation (I went to 30-40 sites, that weren't really that helpful).
If you try to put a timer in a loop - its behavior is NOT intuitive. I'm used to BASIC loops where when you do something to STOP the loop - oddly - it STOPS! :-). Not so with javascript. As an experiment I did a loop with a setTimeout in it, and put the i's of the loop in a div. What chaos! The loop printed out all the i's before the first setTimeout was done! I read that the loop is actually creating a different timer for each loop of the setTimeout. Disaster!
You can stop a timer with clearTimeout(nameoftimer).
I'm guessing if you have a routine that stops a timer, it could be restarted at the bottom of the routine with setTimeout(nameoftimer).
I still haven't figured out why a variable assignment such as var timer = setTimeout ( alert('hello'), 1000 ); would not only assign the variable to the code, but also run the code. Not intuitive.
After going to all the sites and trying their code, I went to W3Schools (not held in high esteem by many) and found code that actually worked! I derived my fiddle from that.
Anyway, thanks for the question. I learned a lot!

Categories