Reputation: 1382
I've tried searching other questions on this site, and I've yet to find one that is encountering the same problem as me:
I'm trying to add an ID to an image every time the image is clicked so I may apply a certain styling to the image. This is the code I've used to try and accomplish this:
<div class="imgThumbnail">
<img src="" />
<img src="" />
</div>
<script type="text/javascript">
$(document).ready(function(){
//hover over thumbnail effect
$('.imgThumbnail img').hover(
function() {
$(this).css({"height":"18vh","width":"18vh"})},
function() {
$(this).css({"height":"17vh","width":"17vh"});
});
//selected effect
$('.imgThumbnail img').click(function(){
(this).attr("id","selected");
});
});
Despite all of my trouble shooting efforts, I've yet to find the problem in my code. I've changed the .attr() in the click function to .clear() to test if I was targeting the correct images, and if the click was being registered. This cleared the image I clicked on, as expected. Then I placed $(this).attr("id", "selected") to my hover function, and it added the styling from my "selected" id as expected.
So why won't the id properly add to the image when I use a click function?
I am new to jQuery. I am also still new to navigating this site, so if you can find the answer else where, I would appreciate redirection. Thanks!
Upvotes: 0
Views: 93
Reputation: 2064
To toggle a class on click make a .click() function and then use toggleClass This will toggle the class everytime you click the selected class. use classes not id's for this kinda stuff
$('.imgThumbnail img').click(function(){
$(this).toggleClass('yourClass');
});
Here's a Fiddle
Upvotes: 1
Reputation: 110
your code is 99% complete. You just forgot the $ before the final this.
This is what your javascript should look like:
$(document).ready(function(){
//hover over thumbnail effect
$('.imgThumbnail img').hover(
function() {
$(this).css({"height":"18vh","width":"18vh"})},
function() {
$(this).css({"height":"17vh","width":"17vh"});
});
//selected effect
$('.imgThumbnail img').click(function(){
$(this).attr("id","selected");
});
});
Upvotes: 1