disable the .click event after the first use - javascript

I am trying to adapt this js code to disable the .click event after you click the button. I am a beginner with js and realy only have a basic understanding. I have tried to use an if statement but that didn't work.
here is the js code:
var sec = ["30% ENTER KEYCODE: Thirty", "25% ENTER KEYCODE: Twenty-five", "20% ENTER KEYCODE: Twenty","15% ENTER KEYCOVE: Fifteen","10% ENTER KEYCODE: Ten","5% EMTER KEYCODE: Five"];
var offset = 30;
//set default degree (360*5)
var degree = 1800;
//number of clicks = 0
var clicks = 0;
$(document).ready(function(){
/*WHEEL SPIN FUNCTION*/
$('#spin').click(function(){
//add 1 every click
clicks ++;
/*multiply the degree by number of clicks
generate random number between 1 - 360,
then add to the new degree*/
var newDegree = degree*clicks;
var extraDegree = Math.floor(Math.random() * 360) + 1;
totalDegree = newDegree+extraDegree;
var colorIndex = Math.ceil(((totalDegree+30) % 360) / 60) -1;
var colorPrev = colorIndex == 0 ? 5 : colorIndex - 1;
var colorNext = colorIndex == 5 ? 0 : colorIndex + 1;
offset = (extraDegree % 60);
var result = sec[colorIndex];
if(offset == 0) {
result ;
} else if (offset <= 30) {
result ;
} else {
result ;
}
$("#answer").html("Answer: " + result);
/*let's make the spin btn to tilt every
time the edge of the section hits
the indicator*/
$('#wheel .sec').each(function(){
var t = $(this);
var noY = 0;
var c = 0;
var n = 700;
var interval = setInterval(function () {
c++;
if (c === n) {
clearInterval(interval);
}
var aoY = t.offset().top;
console.log(aoY);
/*23.7 is the minumum offset number that
each section can get, in a 30 angle degree.
So, if the offset reaches 23.7, then we know
that it has a 30 degree angle and therefore,
exactly aligned with the spin btn*/
if(aoY < 23.89){
console.log('<<<<<<<<');
$('#spin').addClass('spin');
setTimeout(function () {
$('#spin').removeClass('spin');
}, 100);
}
}, 10);
$('#inner-wheel').css({
'transform' : 'rotate(' + totalDegree + 'deg)'
});
noY = t.offset().top;
});
});
});//DOCUMENT READY
here is the original post that I am trying to adapt
https://codepen.io/anon/pen/JGwQva
again I am trying to disable the ability to spin the wheel after you click the spin button.

If you only want to use it once there is a one() method that removes listener after first click
Change:
$('#spin').click(function(){
To
$('#spin').one('click',function(){

There are several hints given by other moderators. Anyways, you may try any of these, lets if this helps.
Simple solution using disabled attribute comes handy.
$(function() {
$('#spin').click(function() {
console.log('clicked..', this);
$(this).prop('disabled', true);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>
Solution using $.one.
$(function() {
$('#spin').one('click', function() {
console.log('clicked..', this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>
Solution using $.on and $.off.
$(function() {
$('#spin').on('click', function() {
console.log('clicked..', this);
$(this).off('click');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>
Solution using some class names.
$(function() {
$('#spin').click(function() {
if ($(this).hasClass('hold')) {
return;
}
$(this).addClass('hold');
console.log('clicked..', this);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="spin">Spin</button>

$('#spin').click(function(){
clicks ++;
if (clicks < 1 ) {
//rest of You code and/or reset clicks variable
}
}
also, change click to $('#spin').on('click',function(){}

var clicks = 0;
$(function () {
$('body').on('click', '#spin', function () {
//
if (clicks > 0) {
return false;
}
// write code here for first click
clicks++;
})
})

Related

how to place a time display box in a time progress bar

i have time progress bar. i use this code.i need time runner inside blue box.
how can i fix it, means when the yellow bar move depends on time need a time
display box.
var timer = 0,
perc = 0,
timeTotal = 2500,
timeCount = 1,
cFlag;
function updateProgress(percentage) {
var x = (percentage/timeTotal)*100,
y = x.toFixed(3);
$('#pbar_innerdiv').css("width", x + "%");
$('#pbar_innertext').text(y + "%");
}
function animateUpdate() {
if(perc < timeTotal) {
perc++;
updateProgress(perc);
timer = setTimeout(animateUpdate, timeCount);
}
}
$(document).ready(function() {
$('#pbar_outerdiv').click(function() {
if (cFlag == undefined) {
clearTimeout(timer);
perc = 0;
cFlag = true;
animateUpdate();
}
else if (!cFlag) {
cFlag = true;
animateUpdate();
}
else {
clearTimeout(timer);
cFlag = false;
}
});
});
#pbar_outerdiv { cursor: pointer; }
You already have the actual time in the updateProgress() method, so its as simple as changing the line setting the percentage to this:
$('#pbar_innertext').text((percentage / 100).toFixed(2) + " s");
JSFiddle: https://jsfiddle.net/McNetic/hnfRe/395/
Edit: With different browser, I now see the next problem: The animation can take much longer than the advertised time of 2500 ms (because of the very high update frequency of 1000 frames per second). So you should do less animation frames and calculate the percentage base on actual time measuring, like this:
https://jsfiddle.net/McNetic/hnfRe/396/
Check this JSFiddle. You can adjust the CSS: colours, sizes, etc to your needs.
Basically I put the text outside the #pbar_innerdiv in a span box.
<div id="pbar_outerdiv">
<div id="pbar_innerdiv"></div>
<span id="pbar_innertext">Click!</span>
</div>
Edit
So I edited the script and I hope now it matches your needs: JSFiddle Link. This is the script I used:
var timer = 0,
perc = 0,
percIncreaser,
timeTotal = 2500, //Only change this value time according to your need
timeCount = 1,
secondsCount=0,
cFlag;
function updateProgress(percentage,time) {
//var x = (percentage/timeTotal)*100;
$('#pbar_innerdiv').css("width", percentage + "%");
$('#pbar_innertext').text(time/1000 + "s");
}
function animateUpdate() {
if(perc < timeTotal) {
perc+=percIncreaser;
secondsCount+=10;
updateProgress(perc,secondsCount);
if(perc>=100) clearTimeout(timer);
else timer = setTimeout(animateUpdate, timeCount);
}
}
$(document).ready(function() {
$('#pbar_outerdiv').click(function() {
percIncreaser = 100/timeTotal*10;
if (cFlag == undefined) {
clearTimeout(timer);
perc = 0;
cFlag = true;
animateUpdate();
}
else if (!cFlag) {
cFlag = true;
animateUpdate();
}
else {
clearTimeout(timer);
cFlag = false;
}
});
});

.ScrollLeft in Firefox issue

I have this script:
<script>
Array.prototype.forEach.call(document.querySelectorAll(".thumbs div"), function ($div) {
$div.style.width = document.querySelectorAll(" img").length * 100 / 4 + "px";
});
document.querySelector("#next").onclick = function () {
var i = 100;
var intervalId = setInterval(function () {
document.querySelector(".thumbs").scrollLeft += 1;
if (i == 0) {
clearInterval(intervalId);
}
i--;
});
};
document.querySelector("#prev").onclick = function () {
var i = 100;
var intervalId = setInterval(function () {
document.querySelector(".thumbs").scrollLeft -= 1;
if (i == 0) {
clearInterval(intervalId);
}
i--;
});
};
</script>
That scrolls the slider thumbs when clicking the next or prev buttons. In Opera and Chrome, it works fine - with one click to the button, .thumbs scrolls 100px. But in Firefox, with one click, it scrolls 1px.
What can I do to fix that?
That's because you aren't passing an interval delay to setInterval, and so Firefox only runs it once. Other browsers seem to take it as if you were passing it 0 (the minimum delay).
Just pass 0 or any value you like, to both of your intervals.
http://jsfiddle.net/ar8au1o6/1/
var intervalId = setInterval(function () {
document.querySelector(".thumbs").scrollLeft += 1;
if (i == 0) {
clearInterval(intervalId);
}
i--;
}, 0); // <-- Set each interval in your code to 0,
// Or any other delay.
// If you set it to 0, the browser will pick the minimum delay.

DIV animation and color change

I'm trying to simulate TCP packet transmission, and hopefully I've made much progress. But now I want to fix two minor issues, that I need help with:
1- I want to highlight the corresponding cell in the table on the bottom of the page as yellow when the packet is being sent, and later when its ack is received, change the color to green.
2- The speed variable got from the input does not work!!
My code is here: http://jsfiddle.net/j26Qc/108/
$(document).ready(function () {
var count = 0;
var items = 0;
var packetNumber = 0;
var speed = 0;
var ssth= $("#ssth").val();
var window_left=0;
for(var i=1;i<=32;i++){
$('#table').append("<div class='inline' id='"+i+"'>"+i+"</div>");
}
document.getElementById(1).style.width=22;
$("button").click(function () {
if (count < ssth) {
if(items==0)
items=1;
else
items = items * 2;
count++;
} else {
items = items + 1;
}
window_left+=20;
window_width=items*20;
document.getElementById("window").style.left= window_left+"px";
document.getElementById("window").style.width=window_width+"px";
speed = $("#speed").val();
createDivs(items);
animateDivs();
});
function createDivs(divs) {
packetNumber = 1;
var left = 60;
for (var i = 0; i < divs; i++) {
var div = $("<div class='t'></div>");
div.appendTo(".packets");
$("<font class='span'>" + packetNumber + "</font>").appendTo(div);
packetNumber++;
div.css({
left: left
/* opacity: 0*/
}).fadeOut(0);
//div.hide();
//left += 20;
}
}
function animateDivs() {
$(".t").each(function (index) { // added the index parameter
var packet = $(this);
packet
.delay(index * 200)
.fadeIn(200)
.animate({left: '+=230px'}, speed)
.animate({left: '+=230px'}, speed)
.fadeOut(200, function () {
packet
.css({
top: '+=20px',
backgroundColor: "#f09090"
})
.text('a' + packet.text());
})
.delay(1000)
.fadeIn(200)
.animate({left:'-=230px'}, speed)
.animate({left:'-=230px'}, speed)
.fadeOut(200, function () {
packet
.css({
top: '-=20px',
backgroundColor: "#90f090"
});
});
}).promise().done(function(){
$(".packets").empty();});
}
});
1.
When it comes to coloring it is best to add an extra variable holding the count of items. A quick and dirty way, without adding a variable and instead using window_left / 20, would be in animateDivs():
// First fade
.fadeIn(200, function() {
$('#table #' + (index + window_left/20)).css({background:'yellow'});
})
// ...
// Second fade
.fadeIn(200, function() {
$('#table #' + (index + window_left/20)).css({background:'green'});
})
And in $("button").click(function () { right after first if{}else{}:
for (var i = 0 ; i < items + window_left / 20; ++i)
$('#table #' + (i)).css({background:'#fff'});
2.
When it comes to the speed you need to convert the value to int:
speed = parseInt($("#speed").val());
// Or
speed = +$("#speed").val();

Change animation speed

I am creating a new "whack-a-mole" style game where the children have to hit the correct numbers in accordance to the question. So far it is going really well, I have a timer, count the right and wrong answers and when the game is started I have a number of divs called "characters" that appear in the container randomly at set times.
I have taken away the "play" button and have replaced it with "easy", "medium" and "hard". When a mode is clicked I want the speed to change. The three button share the class "game_settings"
Here is the code that makes deals with the animation
function randomFromTo(from, to) {
return Math.floor(Math.random() * (to - from + 1) + from);
}
function scramble() {
var children = $('#container').children();
var randomId = randomFromTo(1, children.length);
moveRandom("char" + randomId);
}
var currentMoving = [];
function moveRandom(id) {
// If this one's already animating, skip it
if ($.inArray(id, currentMoving) !== -1) {
return;
}
// Mark this one as animating
currentMoving.push(id);
var cPos = $('#container').offset();
var cHeight = $('#container').height();
var cWidth = $('#container').width();
var bWidth = $('#' + id).width();
var bHeight = $('#' + id).css('top', '395px').fadeIn(100).animate({
'top': '-55px'
}, 6000).fadeOut(100);
maxWidth = cPos.left + cWidth - bWidth;
minWidth = cPos.left;
newWidth = randomFromTo(minWidth, maxWidth);
$('#' + id).css({
left: newWidth
}).fadeIn(1000, function () {
setTimeout(function () {
$('#' + id).fadeOut(1000);
// Mark this as no longer animating
var ix = $.inArray(id, currentMoving);
if (ix !== -1) {
currentMoving.splice(ix, 1);
}
window.cont++;
}, 1000);
});
}
How would I make it so that these settings change in accordance the the difficulty pressed at the beginning?
Fiddle: http://jsfiddle.net/pUwKb/53/
Your buttons do not share the class 'game_ettings', they are inside the div with a class 'game_settings', so the game starts also in case you click between the buttons. modify it like this:
// remove this line
$(".game_settings").find('input').click(
// replace it with...
var AnimationSpeed = 6000;
$(".game_settings").find('input').click(function () {
// here you could set a different timer value for each variant
// or simply send the classname to startplay and handle the
// settings there.
switch($(this).attr('class')) {
case 'easy':
AnimationSpeed = 6000;
break;
case 'medium':
AnimationSpeed = 3000;
break;
case 'hard':
AnimationSpeed = 1000;
break;
}
startplay();
});
In your timer function remove the line:
$("#btnstart").bind("click", startplay);
And in your function moveRandom you use the AnitmationSpeed:
var bHeight = $('#' + id).css('top', '395px').
fadeIn(100).animate({'top': '-55px'}, AnimationSpeed).
fadeOut(100);
You find a working demo here.
What I think you want to do is set the timeInterval according to the game difficulty. This is how I think you might get it to work.
Changes to be made:
html:
//Change
<div class="game_settings">
<div><input class="easy" type="button" value="Easy"></div>
<div><input class="medium" type="button" value="Medium"></div>
<div><input class="hard" type="button" value="Hard"></div>
</div>
//To
<div class="game_settings">
<div><input class="game-speed" id="easy" type="button" value="Easy"></div>
<div><input class="game-speed" id="medium" type="button" value="Medium"></div>
<div><input class="game-speed" id="hard" type="button" value="Hard"></div>
</div>
Sript:
//Change
$(".game_settings").click(function () {
startplay();
});
//To
$(".game-speed").click(function () {
startplay($(this).attr('id'));
});
//Change in startPlay()
startPlay()
play = setInterval(function () {
if (window.cont) {
window.cont--;
scramble();
}
}, 500);
//To
startplay(speed_check) // As it is now expecting a variable
if(speed_check == 'easy'){
play = setInterval(function () {
if (window.cont) {
window.cont--;
scramble();
}
}, 2000);
}
else if(speed_check == 'medium'){
play = setInterval(function () {
if (window.cont) {
window.cont--;
scramble();
}
}, 1000);
}
else if(speed_check == 'hard'){
play = setInterval(function () {
if (window.cont) {
window.cont--;
scramble();
}
}, 400);
}
else{
play = setInterval(function () {
if (window.cont) {
window.cont--;
scramble();
}
}, 1000);
}
Set the time intervals as you like.
Note: This is just an idea what it should be like. You can ofcourse make it more efficient as you know your code better that anyone else.
In DotNet you need to "stop" the storyboard and restart with speed modification.
Dim sb as Storyboard = ctype(Me.FindRessources("Storyboard1"), Storyboard)
sb.Stop
Select Case Level
Case "easy": sb.SpeedRatio = 0.75
Case "medium": sb.SpeedRatio = 1
Case "hard": sb.SpeedRatio = 2.0
End Select
sb.Begin
Perhaps it is the same in JavaScript?

How to put in previous and next function

Can someone give me a hand with this script? I wonder how to put in previous and next function? Start and stop function is working great. Hope that script is readable ok.
Another question.
Is it possible to make previous and next function like when you press previous bttn that script stops and you need to press play bttn to start it again?
Thanks for help.
<script type="text/javascript">
// SET THIS VARIABLE FOR DELAY, 1000 = 1 SECOND
var delayLength = 10000;
function doMove(panelWidth, tooFar) {
var leftValue = $("#mover").css("left");
// Fix for IE
if (leftValue == "auto") { leftValue = 0; };
var movement = parseFloat(leftValue, 10) - panelWidth;
if (movement == tooFar) {
$(".slide img").animate({
"top": -200
}, function() {
$("#mover").animate({
"left": 0
}, function() {
$(".slide img").animate({
"top": 80
});
});
});
}
else {
$(".slide img").animate({
"top": -200
}, function() {
$("#mover").animate({
"left": movement
}, function() {
$(".slide img").animate({
"top": 80
});
});
});
}
}
jQuery(function($){
var $slide1 = $("#slide-1");
var panelWidth = $slide1.css("width");
var panelPaddingLeft = $slide1.css("paddingLeft");
var panelPaddingRight = $slide1.css("paddingRight");
panelWidth = parseFloat(panelWidth, 10);
panelPaddingLeft = parseFloat(panelPaddingLeft, 10);
panelPaddingRight = parseFloat(panelPaddingRight, 10);
panelWidth = panelWidth + panelPaddingLeft + panelPaddingRight;
var numPanels = $(".slide").length;
var tooFar = -(panelWidth * numPanels);
var totalMoverwidth = numPanels * panelWidth;
$("#mover").css("width", totalMoverwidth);
$("#slider").append('Stop');
sliderIntervalID = setInterval(function(){
doMove(panelWidth, tooFar);
}, delayLength);
$("#slider-stopper").click(function(){
if ($(this).text() == "Stop") {
clearInterval(sliderIntervalID);
$(this).text("Start");
}
else {
sliderIntervalID = setInterval(function(){
doMove(panelWidth, tooFar);
}, delayLength);
$(this).text("Stop");
}
});
});
</script>

Categories

Resources