Change div background after certain amounts of clicks - javascript

I have a script that shows the amount of clicks on a button and I want to change the background image of another div after a certain amount of clicks, in this case 5. At the moment the click amount works fine but the other part wont react to it. The second code works if I manually type 5 as the starting value for #click.
This is what I have so far:
$('#button').click(function () {
$('#clicks').html(function (i, val) {
return val * 1 + 1
});
});
if ($('#clicks').html() == 5) {
$("#first").addClass('red');
}
<div id="clicks">0</div>
<div id="first">first</div>
<div id="button">click</div>
#first {
width: 100px;
height:100px;
}
.red {
background:red;
}

You need to check the value after each click modification. also you should compare the returned value with string:
$('#button').click(function () {
$('#clicks').html(function (i, val) {
return val * 1 + 1
});
//check for new value
if ($('#clicks').html() == "5") {
$("#first").addClass('red');
}
});

Try this:
$(function() {
var count = 0;
$('div').click(function() {
if (count++ == 5) {
$(this).addClass('red');
}
})
});
.red {
background-color: red;
}
div {
width: 100px;
height: 100px;
background-color: blue;
}
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<div></div>

Increase the value and check if it's 5 within the click function.
$('#button').click(function () {
$('#clicks').html(function (i, val) {
val++;
if (val == 5)
$("#first").addClass('red');
return val;
});
});
You can also change it every 5 clicks by using the modulus and toggleclass.
$('#button').click(function () {
$('#clicks').html(function (i, val) {
val++;
if (val % 5 == 0)
$("#first").toggleClass('red');
return val;
});
});

Related

Add / remove keywords in textarea doesn't work on cell phones (jquery)

Works fine on a computer. On a computer after you enter a word and press the space bar the word gets wrapped in a box and you get the option to remove it. On a cell phone nothing happens after your press the space bar. It also doesn't limit it to 5 words on a cell phone.
Working jsfiddle: http://jsfiddle.net/1hco43vr/
$('#box a').on('click', function() {
$(this).parent().parent().remove();
console.log('remove disabled');
if ($('#box ul li').length <= 5) {
$('#type').prop('disabled', false);
}
});
}
$('#type').keypress(function(e) {
if (e.which == 32) { //change to 32 for spacebar instead of enter
var tx = $(this).val();
if ($('#box ul li').length > 5) {
$(this).val('');
console.log('add disabled');
$('#type').prop('disabled', 'disabled');
} else {
if (tx) {
$(this).val('').parent().before('<li><span>' + tx + 'x</span></li>');
closer();
}
}
}
});
Instead of using .keypress(), which listens for the keypress JavaScript event (now deprecated), it is preferable to use the input event instead. This is both currently supported and not dependent on a specific input method (it also works if the user pastes the data instead of keying it in, for example). This means that it has a much better chance of behaving consistently across different types of devices.
Each time the user inputs text in the input field, check whether the user has entered a space, before doing something useful: http://jsfiddle.net/7vdtz5jm/2/
function closer() {
$('#box a').on('click', function() {
$(this).parent().parent().remove();
console.log('remove disabled');
if ($('#box ul li').length <= 5) {
$('#type').prop('disabled', false);
}
});
}
$('#type').on('input', function(e) {
var tx = $(this).val();
var array = tx.split(' ');
var limit = 5;
var remainder = '';
if (1 < array.length) { //change to 32 for spacebar instead of enter
if ($('#box ul li').length > limit) {
$(this).val('');
console.log('add disabled');
$('#type').prop('disabled', 'disabled');
} else {
$.each(array, function(i, text) {
if(i < limit && i === array.length - 1 && text) { //no space at the end
remainder = text;
return false;
} else if($('#box ul li').length <= limit) {
if (text) {
$('#type').parent().before('<li><span>' + text + 'x</span></li>');
closer();
};
} else {
$('#type').val('');
console.log('add disabled');
$('#type').prop('disabled', 'disabled');
remainder = '';
return false;
};
})
$('#type').val(remainder);
}
}
});
#box{padding:8px 2px;border:1px solid #CCCCCC;display:block}
#box input,#box input:active,#box input:focus{border:none;background:none;outline:none}
#box ul,#box li,#box input{margin:0;padding:0}
#box ul,#box li{list-style:none}
#box li,#box a{display:inline-block;margin:2px}
#box span{background-color:#EDEDED;padding:3px;color:#666666;border:1px solid #CCCCCC}
#box a{font-size:12px;line-height:12px;color:#666666;text-decoration:none;padding:1px 3px;margin-left:5px;font-weight:bold;background-color:#FFFFFF;vertical-align:top;border:1px solid #CCCCCC;margin-top:-1px}
#box a:hover{background-color:#666666;color:#FFFFFF}
/* why not? */
body{font-family:sans-serif}
#box span{border-radius:5px}
#box a{border-radius:100%;overflow:hidden}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<div id="box">
<ul>
<li><input type="text" id="type"/></li>
</ul>
</div>
<small>*put something in the input above, and press enter.</small>

How to prevent centered text in input button be moved when dynamically changed

I have an input button with a centered text. Text length is changing dynamically with a js (dots animation), that causes text moving inside the button.
Strict aligning with padding doesn't suit because the text in the button will be used in different languages and will have different lenghts. Need some versatile solution. The main text should be centered and the dots should be aligned left to the end of the main text.
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
var dot = '.';
if(dots < 3) {
$('#payDots').val('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').val('processing');
dots = 0;
}
}
<input id="payDots" type="button" value="Pay" class="button">
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
https://jsfiddle.net/v8g4rfsw/1/ (button should be pressed)
The easiest as this is a value and extra elements can't be inserted, would be to just use leading spaces to make the text appear as it's always centered.
This uses the plugin I wrote for your previous question
$.fn.dots = function(time, dots) {
return this.each(function(i,el) {
clearInterval( $(el).data('dots') );
if ( time !== 0 ) {
var d = 0;
$(el).data('dots', setInterval(function() {
$(el).val(function(_,v) {
if (d < dots) {
d++;
return ' ' + v + '.';
} else {
d = 0;
return v.substring(dots, v.length - dots)
}
})
}, time));
}
});
}
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).val('Proccessing').prop('disabled',true).dots(600, 3);
});
});
.button{
text-align: center;
width: 300px;
font-size: 20px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="payDots" type="button" value="Pay" class="button">
You can find updated code below
Click Here
HTML Code
<button id="payDots">
<span>Pay</span>
</button>
JS Code
var dots = 0;
$(document).ready(function() {
$('#payDots').on('click', function() {
$(this).attr('disabled', 'disabled');
setInterval(type, 600);
})
});
function type() {
$('button').css('padding-left','100px','important');
var dot = '.';
if(dots < 3) {
$('#payDots').text('processing' + dot.repeat(dots));
dots++;
}
else {
$('#payDots').text('processing');
dots = 0;
}
}
CSS Code
button{
text-align: left;
width: 300px;
font-size: 20px;
position:relative;
padding-left:130px;
}

Perform click on one div after the other

I hope you understand my problem.
At the moment I have a JS-function that choses randomly a div of a specific Html-Class.
Now i would like to rewrite the function that it picks one div after the other, just like they are ordered in the HTML-content.
How can I do this?
For information: the random selection is made with jquery and looks like this:
function pickrandom() {
var elems = $(".classname");
if (elems.length) {
var keep = Math.floor(Math.random() * elems.length);
console.log(keep);
$(elems[keep]).click();
}
}
Thanks
$(document).on('click', '.classname', function(){
var self = $(this);
var total_items = $('.classname').length; // 10
var index = self.index(); //2 for 3rd element
if (index < total_items) {
setTimeout(function () {
$('.classname').eq(index+1).trigger('click');
}, 3000);
}
});
this will call the next clicks in 3 sec interval
i don't know why you are using a randomizer function.you can allow the user to make that click
Hopefully this helps you - can't see your markup, but it should get you on the right track. I've also changed your .click() to a .trigger('click') which should be quite a bit more dependable.
JavaScript
function pickrandom() {
var elems = $(".classname");
if (elems.length) {
var curTarget = Math.floor(Math.random() * elems.length);
console.log(curTarget);
$(elems[curTarget]).trigger('click');
// Find index of our next target - if we've reached
// the end, go back to beginning
var nextTarget = curTarget + 1;
if( nextTarget > elems.length ) {
nextTarget = 0;
}
// Wait 3 seconds and click the next div
setTimeout( function() { $(elems[nextTarget]).trigger('click'); }, 3000 );
}
}
$("div").click(function() {
var el = $(this);
setTimeout(function() {
console.log(el.text());
el.toggleClass("click");
}, 2000);
});
var random = Math.floor((Math.random() * $("div").length) + 1);
var index = random - 1;
console.log("Random number: ", random);
var clicker = setInterval(function() {
if (index === $("div").length) {
clearInterval(clicker);
console.log("cleared interval");
} else {
$("div").eq(index).click();
index++;
}
}, 2000)
div {
height: 50px;
width: 100%;
border: 2px solid black;
background-color: lightgreen;
margin-bottom: 10px;
text-align: center;
font-size: 30px;
}
.click {
background-color: lightblue;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
Div 1
</div>
<div>
Div 2
</div>
<div>
Div 3
</div>
<div>
Div 4
</div>
<div>
Div 5
</div>
<div>
Div 6
</div>

jQuery when data reach 0 alert

I have this code:
jQuery/JavaScript
$(document).ready(function () {
function min() {
var number = parseInt($('span').html());
return number - 30;
}
function add() {
var number = parseInt($('span').html());
return number + 31;
}
$("#container").click(function () {
$('span').text(min());
});
$("#box").click(function () {
$('span').text(add());
});
var time = parseInt($('b').html());
if (time <= 0) {
alert("AAAAA");
};
});
CSS
#container{
background: #00ff00;
width: 500px;
height:500px;
}
#box{
background: black;
width: 100px;
height:100px;
color: white;
cursor: pointer;
}
HTML
<div id="container">
<span> 60 </span>
<div id="box"> </div>
</div>
when you click on you text in change for +31 and -30 so you will got 61 because default is 60 and but if you click on text in span will change for -30 only and it will display 30 i wish to alert when text in span reach 0 i made this but didn't work.
does any one know how to fix it?
I think that I'm not understanding completely to you. Maybe this the next link can help you.
You have some errors, check the solution.
$(document).ready(function(){
var $span = $('span');
function min() {
var number = parseInt($span.html());
return number - 30;
}
function add() {
var number = parseInt($span.html());
return number + 31;
}
$("#container").click(function(){
$('span').text(min());
checkTime();
});
$("#box").click(function(){
$('span').text(add());
checkTime();
});
function checkTime() {
debugger
var time = parseInt($span.html());
if (time <= 0) {
alert("AAAAA");
};
}
});
Please next time publish your problem in JSfiddle or similar.
I think you're selector to get the span is incorrect. You also need to execute the check after you decrement the value.
$(document).ready(function(){
function min() {
var number = parseInt($('span').html());
return number - 30;
}
function add() {
var number = parseInt($('span').html());
return number + 31;
}
$("#container").click(function(){
$('span').text(min());
CheckValue();
});
$("#box").click(function(){
$('span').text(add());
});
function CheckValue() {
var val = parseInt($('#container > span').html());
if (val <= 0) {
alert("AAAAA");
}
}
);

Random number into div and then let delete divs in sequence. How?

So, i want to make game for my child. Have low experience in JS.
Scenario:
Have for example 4 square divs with blank bg. After refresh (or win) i want to:
Generate random numbers into div (1...4). And show them in them.
Then let player delete those divs by clicking on them, but in sequence how divs are numbered.
*For example after refresh divs have those numbers 2 3 1 4. So, user has to have rights to delete first div numbered 1 (2 3 _ 4) and so on.* If he clicks on 2 it get error , div stays in place, and user can try again delete right one.
It game for learning numbers. I have the begining.
Index.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css.css">
<script src="http://code.jquery.com/jquery-latest.min.js"
type="text/javascript"></script>
</head>
<body>
<div class="grid">
<div id="Uleft"></div>
<div id="Uright"></div>
<div id="Dleft"></div>
<div id="Dright"></div>
</div>
<script>
$(".grid").children( "div" ).on("click", function(){
$(this).css("visibility", "hidden");
});
</script>
</body>
</html>
css.css
.grid {
margin: 0 auto;
width: 430px;
}
#Uleft, #Uright, #Dleft, #Dright {
border: 1px solid black;
width: 200px;
height: 200px;
margin: 5px;
}
#Uright {
float: right;
background-color: red;
}
#Uleft {
float: left;
background-color: blue;
}
#Dleft {
float: left;
background-color: green;
}
#Dright {
float: right;
background-color: yellow;
}
So, i guess i have use jQuery as well, but i dont know how to make it dynamic and different after refresh of page. Please help :)
http://jsfiddle.net/bNa8Z/
There are a few things you have to do. First you have to create a random array which you use sort and Math.random() to do then, you need insert the text in the squares. Find the min of the visible squares and then remove/alert depending if its the min value.
// sort by random
var rnd = [1,2,3,4].sort(function() {
return .5 - Math.random();
});
// map over each div in the grid
$('.grid div').each(function(ii, div) {
$(div).text(rnd[ii]); // set the text to the ii'th rnd
});
function minVisible() {
var min = 1e10; // a big number
$('.grid div').each(function(ii, div) {
// if not visible ignore
if ($(div).css('visibility') === "hidden" ){
return;
}
// if new min, store
var curFloatValue = parseFloat($(div).text());
console.log(curFloatValue);
if (curFloatValue < min) {
min = curFloatValue;
}
});
return min;
}
$(".grid").children( "div" ).on("click", function(){
var clickedFloatValue = parseFloat($(this).text());
if (clickedFloatValue == minVisible()) {
$(this).css("visibility", "hidden");
} else {
alert("sorry little tike");
}
});
Updated jsfiddle http://jsfiddle.net/bNa8Z/2/
Roughly this is what it would look like:
var selected = {};
$('.grid div').each(function(idx){
var is_done = false;
do{
var rand = Math.floor((Math.random()*4)+1);
if( selected[rand] == undefined ){
$(this).html(rand);
selected[rand] = 1;
is_done = true;
}
}while(!is_done);
});
alert("Start the game");
var clicked = [];
$('.grid').on('click', 'div.block', function(){
var num = $(this).html();
if( num == clicked.length + 1 ){
//alert(num + " is correct!");
clicked.push(num);
$(this).addClass("hide");
}else{
alert("Failed!");
}
if( clicked.length == 4 ){
alert("You Won!");
}
});
HTML:
<div class="grid">
<div class="block" id="Uleft"></div>
<div class="block" id="Uright"></div>
<div class="block" id="Dleft"></div>
<div class="block" id="Dright"></div>
</div>
Added CSS:
#Uleft, #Uright, #Dleft, #Dright {
position:absolute;
...
}
#Uright {
left:220px;
top:0px;
background-color: red;
}
#Uleft {
left:0px;
top:0px;
background-color: blue;
}
#Dleft {
left:0px;
top:220px;
background-color: green;
}
#Dright {
left:220px;
top:220px;
background-color: yellow;
}
.hide {
display: none;
}
See the working version at
JSFiddle
You will need to re-"run" the fiddle per game.
please try it. I think that It will help you.
var generated_random_number_sequesce = function(){
var number_array = [];
var number_string = '';
var is_true = true;
while(is_true){
var ran_num = Math.round(1 + Math.random()*3);
if(number_string.indexOf(ran_num) == -1 && ran_num < 5){
number_array[number_array.length] = ran_num;
number_string = number_string + ran_num;
if(number_array.length == 4){is_true = false;}
}
}
return number_array;
}
var set_number_on_divs = function(){
var number_array = generated_random_number_sequesce();
$(".grid").children().each(function(index, element){
$(this).attr('data-div_number' , number_array[index]);
});
}
set_number_on_divs()
var clicked = 0;
$(".grid").children( "div" ).on("click", function(){
clicked += 1;
var current_div_number = $(this).attr('data-div_number');
if( parseInt(current_div_number) == clicked){
$(this).css("visibility", "hidden");
} else{
clicked -= 1;
alert('error');
}
});

Categories