Jay Tanna Jay Tanna - 6 months ago 10
Javascript Question

how to start transition with onclick on div?

I am developing a widget, for this i am using addClass and removeClass method of jquery but some how it is not working please help me with this.

Here is the code:

<!DOCTYPE html>
<html>
<head>
<title>smooth widget</title>
<style type="text/css">
#test
{
transition : all 0.5s ease;
}
.first
{
width: 150px;
height: 30px;
position: fixed;
bottom: 0px;
right: 25px;
}
#prop
{
width: 150px;
height: 30px;
position: fixed;
bottom: 0px;
right: 25px;
background-color: #abc322;
color: white;
text-align: center;
}
.second
{
width: 150px;
height: 300px;
position: fixed;
bottom: 0px;
right: 25px;
box-shadow: 3px 4px 40px grey;
}
</style>
</head>
<body>
<div id="test" class="first">
<div id = "prop">
freight Calculator
</div>
<p>
welcome to freight calculator
</p>
</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script type="text/javascript">


$('#test').click(function(){
$(this).addClass('second');
console.log("hello");
},function(){
$(this).removeClass('second');
});

</script>
</body>
</html>


when i click on the div it should change its class and start transition but it is not working. please identify the mistake that i have done.

Thank you for your time.

Answer

The click method only takes one callback function: the one that should fire on click. You provided two callbacks (one that adds the class and one that removes it). jQuery doesn't know what to do with that, it assumes the first callback is an eventData object and takes the second function as the action to perform on click. This means that on click, all it does is remove the class.

Refer to https://api.jquery.com/click/ to read more about how to use the click() method.

If you provide only one callback it works fine: https://jsfiddle.net/uqmupq3h/