Reputation: 1041
Im trying to create a if statement in jquery but i cant get it to work i have made a js fiddle
also code
HTML:
<div class="playlist-player shrink"></div>
Javascript:
if($('.playlist-player').hasClass('shrink')) {
$(".playlist-player").mousedown(function(){
$(".playlist-player").addClass("enlarge").removeClass("shrink");
});
} else {
$(".playlist-player").mousedown(function(){
$(".playlist-player").addClass("shrink").removeClass("enlarge");
});
}
CSS:
.shrink {background-color:red;}
.enlarge {background-color:blue;}
.playlist-player {height:20px; width:20px;}
Upvotes: 0
Views: 182
Reputation: 73906
Try this:
$(".playlist-player").mousedown(function () {
$(this).toggleClass("enlarge shrink");
// You can also check the console for class
console.log($(this).attr('class'));
});
Upvotes: 0
Reputation: 44740
You don't need if
else
addClass
removeClass
You can do that with toggleClass()
-
$(".playlist-player").mousedown(function () {
$(this).toggleClass("enlarge").toggleClass("shrink");
});
http://jsfiddle.net/mohammadAdil/Uk67u/8/
Upvotes: 3
Reputation: 2878
Might I encourage you to greatly simplify your code:
<div class="playlist-player shrink"></div>
<style type="text/css">
.playlist-player {height:20px; width:20px;background-color:red;}
.enlarge {background-color:blue;}
</style>
<script type="text/javascript">
$(function() {
$('.playlist-player').click(function(){
$(this).toggleClass('enlarge');
});
});
</script>
$(document).ready
(or $(
in my code) to ensure that the div
has loaded when you try to attach the handlerclick
handler (if not, you can replace click
in my example with mousedown
Upvotes: 1
Reputation: 94459
$(".playlist-player").mousedown(function(){
if($(this).hasClass("shrink")){
$(this).addClass("enlarge").removeClass("shrink");
}else{
$(this).addClass("shrink").removeClass("enlarge");
}
});
Working Example http://jsfiddle.net/Uk67u/4/
Upvotes: 1
Reputation: 11971
You're only checking if it has the class once, you want to check after each click:
$('.playlist-player').mousedown(function() {
if ($(this).hasClass('shrink')
$(".playlist-player").addClass("enlarge").removeClass("shrink");
else
$(".playlist-player").addClass("shrink").removeClass("enlarge");
}
Upvotes: 0
Reputation: 856
try this
$(".playlist-player").mousedown(function(){
if ($('.playlist-player').hasClass('shrink')) {
$(".playlist-player").addClass("enlarge").removeClass("shrink");}
else {
$(".playlist-player").addClass("shrink").removeClass("enlarge");}
}
Upvotes: 1