I want to show some text within a class for each click but keep the clicky-class. Shortly, if you click 2 times, you will get a div-text "You clicked two times", you will still be able to click a third time, then you will get "You clicked three times", until the fifth time when everything will hide. Is there any simpel way to do this? I tried with this but couldn't get it to work.
var clicks = 0;
$('.clicky').on('click', function()
{
clicks++;
if(clicks >= 3)
{
$(this).add($('.background')).add($('.hello'));
}
else(clicks >= 5)
{
$(this).add($('.background')).hide();
}
});
http://jsfiddle.net/sLAzY/ This is a working example of the hide function.
Hope you understand what I mean
Have a nice day!
Use a switch statement. Note, because your elements only have class attributes the selectors can match multiple elements. Just something to keep in mind.
Fiddle for testing
var clicks = 0;
$('.clicky').on('click', function(){
var string;
clicks++;
switch(clicks){
case 1:
string = "You clicked one time";
$('.clicky').text(string);
break;
case 2:
string = "You clicked two times";
$('.clicky').text(string);
break;
case 3:
string = "You clicked three times";
$('.clicky').text(string);
break;
case 4:
string = "You clicked four times";
$('.clicky').text(string);
break;
case 5:
$(this).add($(".background")).hide();
break;
}
});
Does this help you. I used JQuery data() instead of a global variable. So this will help you to have multiple elements of clicky class.
<div class="clicky">
aaaa
</div>
<div class="clicky">
bbbb
</div>
<script type="text/javascript" src="jquery.js" ></script>
<script type="text/javascript">
$('.clicky').data('times', 0);
$('.clicky').on('click', function(){
var times = parseInt($(this).data('times')) + 1;
$(this).data('times', times);
if( times >= 3 && times<5)
$(this).addClass('background').addClass('hello');
else if (times >= 5){
$(this).hide('fast');
}
});
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.