How to do this in jQuery? - javascript

I want to transform this code from JavaScript into jQuery.
This is the current code:
var i = 0;
var start = true;
document.getElementById("startclick").addEventListener("click", function() {
if (start) {
start = false;
interval = setInterval(function() {
i++;
document.getElementById('list').innerHTML += "albastru_" + i + '<br>' ;
}, 3000);
} else {
start = true;
clearInterval(interval);
}
});
Here is my attempt:
$x = 0;
$start = true;
$(document).ready(function () {
$('#buton2').on('click',function () {
if($start){
$start = false;
$interval = setInterval(function () {
$x ++;
$('#list').html('<p>albastru_</p>' + $x + '<br>'); }, 1000);
} else {
$start = true;
clearInterval($interval);
}
})
});

You can do something like below. I'm assuming startclick is a button, after you click it .append() will add the required data to #list div after 3 seconds.
Updated Answer with start and stop buttons.
var i = 0;
var start = true;
var interval = null;
$('#startclick').click(function() {
if (interval !== null) return;
interval = setInterval(function() {
i++;
$('#list').append("albastru_" + i + '<br>');
}, 3000);
});
$("#stop").click(function() {
clearInterval(interval);
interval = null;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div id="list">
</div>
<br />
<button id="startclick">START!</button>
<button id="stop">STOP!</button>

Related

js / css flip card game bug in shuffle function

I have created a js memory game. It has a 24-card grid, and it is supposed to shuffle randomly out of a deck of 15 cards in order to create a little variety. The game should be different every time. However, at random the game shuffles the initial deck and builds the board with 11 pairs and one non-pair of cards. Here's the whole js file:
`var score;
var cardsmatched;
var ui = $("#gameUI");
var uiIntro =$("#gameIntro");
var uiStats = $("# gameStats");
var uiComplete = $("#gameComplete");
var uiCards = $("#cards");
var uiScore = $(".gameScore");
var uiReset = $(".gameReset");
var uiPlay = $("#gamePlay");
var uiTimer = $("#timer");
var matchingGame = {};
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
$(function(){
init();
});
function init() {
uiComplete.hide();
uiCards.hide();
playGame = false;
uiPlay.click(function(e){
e.preventDefault();
uiIntro.hide();
startGame();
});
uiReset.click(function(e){
e.preventDefault();
uiComplete.hide();
reStartGame();
});
}
function startGame(){
uiTimer.show();
uiScore.html("0 seconds");
uiStats.show();
uiCards.show();
score = 0;
cardsmatched= 0;
if (playGame == false) {
playGame = true;
matchingGame.deck.sort(shuffle);
for (var i=0; i<25; i++){
$(".card:first-child").clone().appendTo("#cards");
}
uiCards.children().each(function(index) {
$(this).css({
"left" : ($(this).width() + 20) * (index % 6),
"top" : ($(this).height() + 20) * Math.floor(index / 6)
});
var pattern = matchingGame.deck.pop();
$(this).find(".back").addClass(pattern);
$(this).attr("data-pattern",pattern);
$(this).click(selectCard);
});
timer();
};
}
function timer(){
if (playGame){
scoreTimeout = setTimeout(function(){
uiScore.html(++score = "seconds");
timer();
}, 1000);
};
};
function shuffle() {
return 0.5 - Math.random();
}
function selectCard(){
if($(".card-flipped").size()> 1){
return;
}
$(this).addClass("card-flipped");
if($(".card-flipped").size() == 2) {
setTimeout(checkPattern, 1000);
};
};
function checkPattern(){
if (isMatchPattern()) {
$(".card-flipped").removeClass("card-flipped").addClass("card-removed");
if(document.webkitTransitionEnd){
$(".card-removed").bind("webkitTransitionEnd", removeTookCards);
}else{
removeTookCards();
} else {
$(".card-flipped").removeClass("card-flipped");
}
}
function isMatchPattern(){
var cards = $(".card-flipped");
var pattern = $(cards[0]).data("pattern");
var anotherPattern = $(cards[1]).data("pattern");
return (pattern == anotherPattern);
}
function removeTookCards() {
if (cardsmatched < 12) {
cardsmatched++;
$(".card-removed").remove();
}else{
$(".card-removed").remove();
uiCards.hide();
uiComplete.show();
clearTimeout(scoreTimeout);
}
}
function reStartGame(){
playGame = false;
uiCards.html("<div class='card'><div class='face front'></div><div class='face back'></div></div>");
clearTimeout(scoreTimeout);
matchingGame.deck = ['grilledfish', 'grilledfish','barbacoa', 'barbacoa','tripa', 'tripa','bajafish', 'bajafish','carneasada', 'carneasada','carnitas', 'carnitas', 'chorizoasado','chorizoasado','shrimptaco','shrimptaco','decabeza','decabeza','alpastor', 'alpastor','dorados','dorados', 'lengua','lengua','chicharron','chicharron','sudados','sudados', 'polloasado','polloasado',];
startGame();
}
`

How to run a function in jQuery for 15 times

I have a jQuery function
setInterval(function () {
secondPlay()
}, 1000);
setInterval(function () {
secondPlay1()
}, 1000);
function secondPlay() {
$("body").removeClass("play");
var aa = $("ul.secondPlay li.active");
var ii = $('ul.secondPlay li:last-child').val();
if (aa.html() == undefined) {
aa = $("ul.secondPlay li").eq(0);
aa.addClass("before")
.removeClass("active")
.next("li")
.addClass("active")
.closest("body")
.addClass("play");
}
if (aa.is(":last-child")) {
$("ul.secondPlay li").removeClass("before");
aa.addClass("before").removeClass("active");
aa = $("ul.secondPlay li").eq(0);
aa.addClass("active")
.closest("body")
.addClass("play");
}
else {
$("ul.secondPlay li").removeClass("before");
aa.addClass("before")
.removeClass("active")
.next("li")
.addClass("active")
.closest("body")
.addClass("play");
}
}
I want to run this function for 15 times. How can I run it ?
Declare a variable as a counter. Increment that variable eachtime you calling the function. If the variable reaches 15, the stop the setInterval() by using clearInterval() function
var counter = 1;
var interval = setInterval(function () {
if (counter == 15) {
clearInterval(interval);
}
secondPlay()
counter++;
}, 1000);
You can use following code as reference.
(function(){
var count = 0;
var interval = setInterval(function(){
if(count>15){
window.crearInterval(interval);
}
else{
document.getElementById("lblCount").innerHTML = count;
count++;
}
},1000);
})()
<p id="lblCount"></p>
Try This
var timePlyed = 0;
function secondPlay() {
timePlyed++;
console.log(timePlyed);
if (timePlyed != 15) {
secondPlay();
}
}
secondPlay();
Enclose them in a for loop?
for (i = 0; i < 15; i++) {
...
}
you can use timeout function:
function secondPlay(i){
console.log(i);
}
function test(){
for(var i = 0; i < 15; i++){
setTimeout(function(){
secondPlay(i);
}, i * 1000);
}
}
call test() to execute the function.
Instead of setInterval, you could use a timeout:
var i = 0;
function secondPlay1() {
// do function
setTimeout(function() {
if (i < 15) {
i++;
secondPlay1();
}
}, 1000);
}

how to clear Interval on Mouse Over in java script?

<script type="text/javascript">
var images=["cod.jpg","cod2.jpg","cod3.jpg","cod4.jpg"];
var i=0;
window.onload=function(){
changeimage();
var stopinterval = setInterval(changeimage,3000);
}
function changeimage(){
if(i==images.length||i>images.length){
i=0;
}
document.getElementById('metroslider').src=images[i];
i++;
}
function stopanim(){
clearInterval(stopinterval);
}
</script>
**body is below **
<div class="sliderbtns" onMouseMove="stopanim();">
But its not working please help me how to stop the interval using On mousOver function .
Thanks .
var images = ["cod.jpg", "cod2.jpg", "cod3.jpg", "cod4.jpg"];
var i = 0;
var stopinterval;
window.onload = function() {
changeimage();
stopinterval = setInterval(changeimage, 333);
}
function changeimage() {
document.querySelector('div').innerHTML = i;
i++;
}
function startAnim() {
if (stopinterval === null) {
stopinterval = setInterval(changeimage, 333);
}
}
function stopanim() {
if (stopinterval) {
clearInterval(stopinterval);
stopinterval = null;
}
}
<div onmouseover="stopanim()" onmouseout="startAnim()">mouse over to stop</div>

Updating interval dynamically - jQuery or Javascript

I have two "stopwatches" in my code (and I may be adding more). This is the code I currently use below - and it works fine. But I'd really like to put the bulk of that code into a function so I'm not repeating the same code over and over.
When I tried doing it though, I could get it working - I think it was because I was passing stopwatchTimerId and stopwatch2TimerId into the function and it may have been passing by reference?
How can I reduce the amount of code repetition here?
var stopwatchTimerId = 0;
var stopwatch2TimerId = 0;
$('#stopwatch').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
$(this).addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch-seconds').val()) || 0;
$('#stopwatch-seconds').val(currentValue + 1).change();
}, 1000);
}
});
$('#stopwatch2').click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(stopwatch2TimerId);
}
else {
$(this).addClass('active');
stopwatch2TimerId = setInterval(function () {
var currentValue = parseInt($('#stopwatch2-seconds').val()) || 0;
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
});
As you can see, it's basically the same code in each except for stopwatchTimerId and $('#stopwatch-seconds') (and the same vars with 2 on it for the other one).
This won't pollute global scope and also you don't need to do any if-else statements. Just add data-selector to your new elements :)
<input id="stopwatch" type="text" data-selector="#stopwatch-seconds"/>
<input id="stopwatch2" type"text" data-selector="#stopwatch2-seconds"/>
$('#stopwatch stopwatch2').click(function () {
var $element = $(this),
interval = $element.data('interval');
selector = $element.data('selector');;
if ($element.hasClass('active')) {
$element.removeClass('active');
if (interval) {
clearInterval(interval);
}
}
else {
$element.addClass('active');
$element.data('interval', setInterval(function () {
var currentValue = parseInt($(selector).val()) || 0;
$(selector).val(currentValue + 1).change();
}, 1000));
}
});
function stopwatch(id){
$('#' + id).click(function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active');
clearInterval(window[id]);
}
else {
$(this).addClass('active');
window[id] = setInterval(function () {
var currentValue = parseInt($('#' + id + '-seconds').val()) || 0;
$('#' + id + '-seconds').val(currentValue + 1).change();
}, 1000);
}
});
}
$(function(){
stopwatch("stopwatch");
stopwatch("stopwatch2");
});
You could do something like this (code is not very nice, you can improve it):
var stopwatchTimerId;
$('#stopwatch').click(function () {
doStopWatch(1);
});
$('#stopwatch2').click(function () {
doStopWatch(2);
});
var doStopWatch = function(option){
var stopWatch = option===1?$('#stopwatch'):$('#stopwatch2');
if (stopWatch.hasClass('active')) {
stopWatch.removeClass('active');
clearInterval(stopwatchTimerId);
}
else {
stopWatch.addClass('active');
stopwatchTimerId = setInterval(function () {
var currentValue = option===1?(parseInt($('#stopwatch-seconds').val()) || 0):(parseInt($('#stopwatch2-seconds').val()) || 0);
if(option===1)
$('#stopwatch-seconds').val(currentValue + 1).change();
else
$('#stopwatch2-seconds').val(currentValue + 1).change();
}, 1000);
}
}
Try
var arr = $.map($("div[id^=stopwatch]"), function(el, index) {
el.onclick = watch;
return 0
});
function watch(e) {
var id = this.id;
var n = Number(id.split(/-/)[1]);
if ($(this).hasClass("active")) {
$(this).removeClass("active");
clearInterval(arr[n]);
} else {
$(this).addClass("active");
arr[n] = setInterval(function() {
var currentValue = parseInt($("#" + id + "-seconds").val()) || 0;
$("#" + id + "-seconds").val(currentValue + 1).change();
}, 1000);
}
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js">
</script>
<div id="stopwatch-0">stopwatch1</div>
<input type="text" id="stopwatch-0-seconds" />
<div id="stopwatch-1">stopwatch2</div>
<input type="text" id="stopwatch-1-seconds" />

Select value inside object

How can I get the second value from videoid:uoSDF234and make it countdown ?
first I need "videoid":"uoSDF234" be the first countdown then next will be "videoid":"0apq3ss" and so on (if I add more data).
when I click the stop button, label id="vstopresult" will show the stopped videoid and second.
the countdown will looping for each videoid in videolist.
var videoinfo = [{"startdatetime":"2014-12-21 00:23:14","totalsecondrun":"2019402310","videolist":
[{"videoid":"uoSDF234","second":"10"},{"videoid":"0apq3ss","second":"14"}]}];
// JavaScript Document
var calduration = function(){
$.each(videoinfo, function(i, obj) {
$("#vstart").append(obj.startdatetime);
$("#vtotoals").append(obj.totalsecondrun);
$("#vid").append(videoinfo[0].videolist[0].videoid);
$("#vlefts").append(videoinfo[0].videolist[0].second);
var output = $("#vlefts");
var isPaused = false;
var time = videoinfo[0].videolist[0].second;
var t = window.setInterval(function() {
if(!isPaused) {
time--;
output.text(time);
}
if (time == 0){
clearInterval(t);
}
}, 1000);
//with jquery
$("#vpause").on('click', function(e) {
e.preventDefault();
isPaused = true;
});
$("#vplay").on('click', function(e) {
e.preventDefault();
isPaused = false;
});
$("#vstop").on('click', function(e) {
clearInterval(t);
$("#vstopresult").append(time);
});
});
};
calduration();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div>
<label id="vstart"></label><br>
<label id="vtotoals"></label><br>
<label id="vid"></label><br>
<label id="vlefts"></label><br>
<input type="button" value="play" id="vplay"/>
<input type="button" value="pause" id="vpause"/>
<input type="button" value="stop" id="vstop"/><br>
<label id="vstopresult"></label>
</div>
One crude possibility is to use setInterval, an example may be.
var videoinfo = [{
"startdatetime": "2014-12-21 00:23:14",
"totalsecondrun": "2019402310",
"videolist": [{
"videoid": "uoSDF234",
"second": "10"
}, {
"videoid": "0apq3ss",
"second": "14"
}]
}],
index = 0,
timerEl = document.getElementById('timer'),
countDown = 0,
intervalId;
function startCountdown() {
if (index < videoinfo[0].videolist.length) {
countDown = videoinfo[0].videolist[index].second;
intervalId = setInterval(function () {
timerEl.textContent = countDown;
if (countDown < 1) {
clearInterval(intervalId);
index += 1;
setTimeout(function () {
startCountdown();
}, 1000);
} else {
countDown -= 1;
}
}, 1000);
}
}
startCountdown();
<div id='timer'></div>

Categories