Reputation: 868
I have a bunch of images and I want to add / remove a border and a box shadow on click. I thought it would be very simple, but it seems i am overlooking something here.
html:
<img class='unselected' src='/images/dot.en.hc.png' alt='dot' title='dot' />
jquery:
$('img').click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass('selected').addClass('unselected');
} else {
$(this).removeClass('unselected').addClass('selected');
}
});
css:
.selected {
border: 2px solid #0F0;
box-shadow: 0px 0px 3px 2px #0F0;
transition: border 0.2s, box-shadow 0.2s;
}
.unselected {
border: 2px solid #FFF;
box-shadow: 0px 0px 0px 0px #0F0;
transition: border 0.2s, box-shadow 0.2s;
}
EDIT: as the code above seems to be fine, I am printing here the full code that I have on the website (I just started this little site now to test few things, so it is quite empty):
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script>
$('img').click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass('selected').addClass('unselected');
} else {
$(this).removeClass('unselected').addClass('selected');
}
});
</script>
<style>
img {
max-width: 50px;
}
.selected {
border: 2px solid #0F0;
box-shadow: 0px 0px 3px 2px #0F0;
transition: border 0.2s, opacity 0.2s, filter 0.2s;
opacity: 1;
filter: alpha(opacity = 100);
}
.unselected {
border: 2px solid #FFF;
box-shadow: 0px 0px 0px 0px #0F0;
transition: border 0.2s, opacity 0.2s, filter 0.2s;
opacity: 0.8;
filter: alpha(opacity = 80);
}
</style>
</head>
<body>
<form method="post" enctype="multipart/form-data" action="link.php">
<input type="hidden" name="log" value="1"/>
<img class='unselected' src='/images/dot.en.hc.png' id='dot.en.hc' alt='dot.en.hc' title='dot.en.hc' />
</form>
</body>
</html>
Upvotes: 0
Views: 1938
Reputation: 15112
Use .toggleClass() instead of adding and removing the class.
Also, wrap it with $(document).ready
$(document).ready(function () {
$('img').click(function () {
$(this).toggleClass('selected unselected');
});
});
Upvotes: 2
Reputation: 7031
what about checking if the DOM is ready and or that the images have loaded
also with code below:
ready(): http://api.jquery.com/ready/
// wait until DOM is ready
$(document).ready(function(){
// wait until all images are loaded
$(window).on("load", function(){
$('img').click(function() {
if ($(this).hasClass("selected")) {
$(this).removeClass('selected').addClass('unselected');
} else {
$(this).removeClass('unselected').addClass('selected');
}
});
});
});
Upvotes: 0
Reputation: 610
$('img').click(function() {
if( $(this).hasClass('selected') ) {
$(this).toggleClass(' unselected selected');
}
else{
$(this).addClass('selected');
}
});
Check the working & updated fiddle
Upvotes: 0