Wanting to learn
Wanting to learn

Reputation: 468

remove opacity to all images but one clicked with jquery

How can I remove the opacity off all the elements which were not clicked. I have a set of images in a grid pattern. I'd like to be able to click anyone of them to get the rest to fade away. I can do it now but I'd like to have it be more dynamic.

<script>
$(document).ready(function() { 
 $('#grid').click(function() {
  $('#book').animate({
   opacity: '0'.
   }, 1500, function() {
             });
         });
     });
 </script>

</head><body>

    <div class="portfolio">
     <ul id="grid">
       <li><a href="#"id="book"><img src="1.jpg"></a></li>
       <li><a href="#"id="book1"><img src="2.jpg"></a></li>
       <li><a href="#"id="book2"><img src="3.jpg"></a></li>
       <li><a href="#"id="book3"><img src="4.jpg"></a></li>
       <li><a href="#"id="book4"><img src="5.jpg"></a></li>
       <li><a href="#"id="book5"><img src="6.jpg"></a></li>
       <li><a href="#"id="book6"><img src="7.jpg"></a></li>
       <li><a href="#"id="book7"><img src="8.jpg"></a></li>   
       <li><a href="#"id="book8"><img src="9.jpg"></a></li>   
    </ul></div>

I'm thinking something like, if id does not contain id clicked opacity=0

Upvotes: 2

Views: 285

Answers (2)

Roko C. Buljan
Roko C. Buljan

Reputation: 206268

You don't need such a mess with IDs, keep it simple.

<div class="portfolio">
 <ul id="grid">
   <li><a href="#"><img src="1.jpg"></a></li>
   <li><a href="#"><img src="2.jpg"></a></li>
   <li><a href="#"><img src="3.jpg"></a></li>
   <li><a href="#"><img src="4.jpg"></a></li>
   <li><a href="#"><img src="5.jpg"></a></li>
   <li><a href="#"><img src="6.jpg"></a></li>
   <li><a href="#"><img src="7.jpg"></a></li>
   <li><a href="#"><img src="8.jpg"></a></li>   
   <li><a href="#"><img src="9.jpg"></a></li>   
</ul>
</div>

every event (click in your case) is delegated to an element, known in JS as target.
jQuery for your case also has some nice selector as .siblings() which will target all other elements just not the current one.

$(function() { 
 $('#grid li').click(function() {
   $(this).siblings().animate({opacity: '0'}, 1500);
 });
});

http://jsfiddle.net/Cnjjx/

Upvotes: 4

smakateer
smakateer

Reputation: 556

Have you tried using CSS? Maybe have two classes img.clicked { opacity=1.0; } img.notClicked { opacity=0.0; } Then use jQuery to set the classes instead.

Upvotes: 0

Related Questions