I have this code :
var n = 0; // << I want save value of this var
$('.next').click(function () { // << after this method run
n++
});
function run() {
setInterval(function () {
n++;
var slideId = '#' + "slide" + (n);
var dotId = '#' + "dot" + (n);
if (n == settings.slideNumber) {
n = 0;
}
var lastSlideId = '#' + "slide" + (n + 1);
var lastDotId = '#' + "dot" + (n + 1);
$(slideId).css({display: 'none'});
$(dotId).css({backgroundColor: '#1a1a1a'});
$(lastSlideId).css({display: 'block'});
$(lastDotId).css({backgroundColor: '#0AC986'});
}, 2000);
}
run();
After the click event occurred , run method will start from fist and value of n will be zero again .
How i can save the value of n var after click event ?
( Consider that I wrote this method inside a jquery plugin )
You can declare n as the global variable, to keep up to date with the latest value of n.
Also, the click event should be outside of the run function, otherwise, each time you execute run function it will attach a new event listener for the button click.
I have created a sample as per your question. Hope it helps.
let n = 0;
$('#btn').click(function() {
n++;
console.log("Value of n::",n)
});
function run() {
console.log("Value of n::",n)
}
run();
$('#run').click(run);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="btn">Click</button>
<button id="run">Run</button>
Related
I can't figure out why these if statements aren't working. I have tried setting the second one to else if as well and it's still not working.
Basically I want to the code to add 1 to the count variable whenever a button is pressed. The problem is that even though the count++ is working, the if statements aren't registering and I can just keep playing around in the if (count== 0) section.
var player = "X";
var comp = "O";
var count = 0;
console.log(count);
//Code for turn 1
if (count == 0) {
//Code for Div 1
$("#1").one("click", function(){
console.log("hit")
count++;
console.log(count)
if ( $('#1').children().length == 0 ){
$("#1").append("<p>" + player + "</p>");
$("#5").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
});
//Code for Div 2
$("#2").one("click", function(){
console.log("hit")
count++;
console.log(count);
if ( $('#2').children().length == 0 ){
$("#2").append("<p>" + player + "</p>");
$("#5").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
});
if (count == 1){
$("#2").one("click", function(){
count++;
if ( $('#2').children().length == 0 ){
$("#2").append("<p>" + player + "</p>");
$("#3").append("<p>" + comp + "</p>");
}
else {
console.log("full");
}
})
console.log(count);};
Any logic that needs to be executed on each click must be triggered by that click. Right now, the ifs at the top level are only run once, not in response to clicks.
You're using $("#1").one, which by definition only works once:
Description: Attach a handler to an event for the elements. The
handler is executed at most once per element per event type. (source)
Change all .one's to .on.
I have a script which I am using.I would like it so when user clicks once it changes a var to 0 when user clicks again it changes var to 3 and then repeats. So click again would be 0 another would be 3 at the moment the part I want to detect 2nd click is 'mousemove'.Can anybody help please below is my code.
window.addEventListener('load', function () {
function go() {
i = i < height ? i + step : 1;
m.style.marginTop = -i + 'px';
}
var i = 0,
step = 3,
space = ' ';
var m = document.getElementById('marquee');
var t = m.innerHTML;
m.innerHTML = t + space;
m.style.position = 'absolute';
var height = (m.clientHeight + 1);
m.style.position = '';
m.innerHTML = t + space + t + space + t + space + t + space + t + space + t + space + t + space;
// first click
m.addEventListener('click', function () {
step = 0;
}, true);
// second click
m.addEventListener('mousemove', function () {
step = 3;
}, true);
var x = setInterval(go, 50);
}, true);
Your question is a bit unclear, but if you want to alternate between 0 and 3 on each click:
var result = document.querySelector('#result')
var step = 0
document.querySelector('#m').addEventListener('click', function (event) {
// `0` is false-y in JS, so if `step === 0`, then it'll be set to 3
// otherwise, it'll be set to 0 (`3` is truth-y)
step = step ? 0 : 3
result.innerHTML = 'step is ' + step
// if you want to do something with `step`:
if (step === 0) {
// do something
} else {
// do something else
}
})
<button id='m'>click me</button>
<p id='result'></p>
One approach is to set up a click counter. If the click counter is even then set step to zero, if odd then set it to 3.
var clickCounter = 0;
m.addEventListener('click', function () {
step = (clickCounter++ % 2 === 0 ? 3 : 0);
}, true);
DEMO: http://jsfiddle.net/byrkfvvk/
Another approach is to have an internal property which you use as a boolean toggle.
document.getElementById('button').addEventListener('click', function () {
this.active = !this.active;
step = (this.active ? 3 : 0);
}, true);
DEMO: http://jsfiddle.net/h8hu4sm0/1/
This script generate divs with cloud images that fly from left to right with random height and intervals. It generally works but it keeps incrementing divs "id" infinitely. I can't figure out how to reset the counter being safe that never two identical "id"s will exist in the same time.
function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
function cloud(type,time,nr){
$("#sky").append("<div id=\"cloudFL"+nr+"\" class=\"cloud"+type+"\" ></div>");
setTimeout(function() {
$("#cloudFL"+nr).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
left:'100%',
},time,'linear',function(){$(this).remove();
});
}, Math.floor(Math.random() * t1));
};
function wave(){
var tx = 0;
setInterval(function(){
cloud(1,t1,nr);
nr++;
var n = $( "div.cloud1" ).length;
$( "span" ).text( "There are " + n +" n and "+ tx +" tx")
if(tx < n){tx = n}
else(tx = 1)
},500);
};
wave()};
cloudgenerator()
In the bottom, there is an instruction that checks if number of divs is starting to drop and presents those values in span for debugging.
Quick and easy solutionYou could loop through the id's in JQuery, starting from the lowest number, until you find a JQuery selector that yields 0 results...
var newid = 0;
var i = 1;
while(newid == 0) {
if( $('#cloudFL' + i).length == 0 ) { newid = i; }
else { i++; }
}
JSFIDDLE DEMO
Alternative solution (scalable)
Given that you may have many clouds onscreen at one time, you could try this alternative approach.
This approach creates an array of 'used ids' and the wave function then checks if any 'used ids' are available before creating a new id for the cloud function. This will run quite a bit more efficiently that then above 'quick fix solution' in situations where many clouds appear on screen.
function cloudgenerator(){
var nr=1;
var t1 = 20000;
var t2 = 50000;
var spentids = [];
function cloud(type,time,id){
$("body").append('<div id="' + id + '" class="cloud' + type + '" >' + id + '</div>');
setTimeout(function() {
$('#'+id).css({top:Math.floor(Math.random() * 400)+'px'}).animate({
left:'100%',
},time,'linear',function(){
spentids.push( $(this).attr('id') );
$(this).remove();
});
}, Math.floor(Math.random() * t1));
};
function wave(){
setInterval(function(){
if(spentids.length == 0) {
cloud(1,t1,"cloudFL" + nr);
nr++;
} else {
spentids = spentids.sort();
cloud(1,t1,spentids.shift());
}
},500);
};
wave()};
cloudgenerator()
JSFIDDLE DEMO - ALTERNATIVE
Why not get the timestamp and add this to your id?
If you donĀ“t need the ids i would stick to #hon2a and just add the styling to the class and remove the ids.
And another solution:
You could make a check if ID xyz is used. Like this e.g.
var cloudCount = jQuery('.cloud20000').length + jQuery('.cloud50000').length + 10;
for(var i = 0; i <= cloudCount; i++) {
if(jQuery('#cloudFL' + i).length <= 0) {
nr = i;
return false;
}
}
cloud(1,t1,nr);
i have the following code to count clicks on a div
$('.ps-next').click(function () {
setTimeout($('#currentImage').html(parseInt($('#currentImage').html(), 10) - 1), 10000);
});
$('.ps-prev').click(function () {
setTimeout($('#currentImage').html(parseInt($('#currentImage').html(), 10) + 1), 10000);
});
i would like to count clicks but i want to put a delay of 1 second between clicks. or at least not count fast clicks can anyone help me.
I use a slightly different approach than most here.
The event object has a timeStamp property, so I compare that to the previous timestamp. Here's how I'd approach the situation...
var lastClick,
$count = $('.count');
$('.stepper').on('click', function(e){
// If we have a lastClick value or the current timeStamp
// minus lastClick is greater than 1000 ( 1 second ), go to work.
if ( !lastClick || lastClick && e.timeStamp - lastClick > 1000 ) {
var $stepper = $(this);
$count.text(function(i, txt){
var current = +txt;
return current + ( $stepper.is('.up') ? 1 : -1 );
});
lastClick = e.timeStamp;
}
});
Along with this HTML.
<div class="stepper up">Up</div>
<div class="count">5</div>
<div class="stepper down">Down</div>
Here is a quick demo: http://jsbin.com/iruXisOn/1/edit
you can use this jquery plugin
(function ($) {
$.fn.oneClickPerTime = function (callback,timeDelay) {
var __this = this;
flagOneClick = 1;
return this.each(function () {
$(__this).click(function() {
if (flagOneClick==0)
return;
flagOneClick = 0;
setTimeout(function() {
flagOneClick = 1;
},timeDelay);
callback(this);
});
});
}
})(jQuery);
then call function and must define the timeout, ex: 1000 (1 second)
$('.ps-prev').oneClickPerTime(function(){
//callback
},1000);
I have a problem, I have 3 button lets say it's called #pos1, #pos2 and #pos3.
I want to makes it automatically click #pos1 button in 2 seconds, after that click the #pos2 after another 2 seconds, and #pos3 after another 2 seconds,
after that back to the #pos1 in another 2 seconds and so on via jQuery.
HTML
<button id="pos1">Pos1</button>
<button id="pos2">Pos2</button>
<button id="pos3">Pos3</button>
Anyone can help me please?
Try
$(function() {
var timeout;
var count = $('button[id^=pos]').length;
$('button[id^=pos]').click(function() {
var $this = $(this);
var id = $this.attr('id');
var next = parseInt(id.substring(4), 10) + 1;
if( next >= count ){
next = 1
}
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
$('#pos' + next).trigger('click');
}, 2000);
})
timeout = setTimeout(function() {
$('#pos1').trigger('click');
}, 2000);
})
var posArray = ["#pos1", "#pos2", "#pos3"];
var counter = 0;
setInterval(function() {
$(posArray[counter]).triggerHandler('click');
counter = ((counter<2) ? counter+1 : 0);
}, 2000);
That should do the trick, though you did not mention when you want it to stop running.
Well I don't know what you already have but technically it could be done via triggerHandler()
var currentPos = 1,
posCount = 3;
autoclick = function() {
$('#pos'+currentPos).triggerHandler('click');
currentPos++;
if(currentPos > posCount) { currentPos = 1; }
};
window.setInterval(autoclick,2000);
If I have understood you question right, you need to perform click in a continuous loop in the order pos1>pos2>pos3>pos1>pos2 and so on. If this is what you want, you can use jQuery window.setTimeout for this. Code will be something like this:
window.setTimeout(performClick, 2000);
var nextClick = 1;
function performClick() {
if(nextClick == 1)
{
$("#pos1").trigger("click");
nextClick = 2;
}
else if(nextClick==2)
{
$("#pos2").trigger("click");
nextClick = 3;
}
else if(nextClick == 3)
{
$("#pos3").trigger("click");
nextClick = 1;
}
window.setTimeout(performClick, 2000);
}
This is quite buggy but will solve your problem.
using setInterval()
Calls a function or executes a code snippet repeatedly, with a fixed time delay between each call to that function.
var tempArray = ["pos1", "pos2", "pos3"]; //create an array to loop through
var arrayCounter = 0;
setInterval(function() {
$('#' + tempArray[arrayCounter ]).trigger('click');
arrayCounter = arrayCounter <2 ? arrayCounter +1 : 0;
}, 2000);
fiddle here
check your console for fiddle example