Hi every one I’v been learning jquery for about 3 months now and I cant figure this out.
What I am trying to do is change the background of a div (.box) by a click. I know how to do that for one click but I don’t know how to change the backgrounColors upon different clicks. I would like to implement some sort of an if statement that says that if the background of the current class==red than on click make the new current class yellow. In this example I can’t get the background color to yellow and I really want to be yellow upon the third click of the div. in the future I like the 4th click create even another backgroundColor.
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<style type="text/css">
.box{
width:200px;
height:200px;
background-color:green;
}
.red{
width:200px;
height:200px;
background-color:red;
}
.yellow{
width:200px;
height:200px;
background-color:yellow;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
$('.box').click(toRed)
function toRed(e){
$(this).addClass('red');
}
if($('this').hasClass('red')){
$(this).removeClass('red')
.addClass('yellow');
}
});
</script>
</head>
<body>
<div class="box"></div>
</body>
</html>
so in conclusion im basically trying to change the backgroundcolor of the div when I click on it multiple times to different distinct colors each time.
and why doesn’t my code work.
Thank you for reading and thanks for your response in advance.
Are you looking for something like this jsFiddle example?