tags:

views:

26

answers:

3

Two questions please:

1) In this example, http://jsbin.com/ijuli, how do I make it so when one image is clicked, the other un-hidden .clickSave divs go back to hidden.

2) Is there a more efficient way to write the JS code?

Jquery

$(".clickSave").hide();  
    $(".one").click(function() {
    $(".clickSave.one").toggle(); 
});

$(".clickSave").hide();  
    $(".two").click(function() {
    $(".clickSave.two").toggle(); 
});

$(".clickSave").hide();  
    $(".three").click(function() {
    $(".clickSave.three").toggle(); 
});

Thank you so much in advance! I'm so confused by all this.

+1  A: 

You can do this:

$(document).ready(function() {
    $(".clickSave").hide();

    $("a").click(function() {  // attaches click handler to links       
        // toggle clickSave element inside the clicked link
        var ele = $(".clickSave", this).toggle();
        // hide all other visible clickSave elements
        $(".clickSave:visible").not(ele).hide(); 
    });
}); 

Demo

Felix Kling
This would hide all of them, every time ;)
Nick Craver
@Nick Craver: Yeah, I just realized it ;)
Felix Kling
@Felix - Now it doesn't toggle ;)
Nick Craver
@Nick: Oh damn.... :-D It is definitely too late here... I should go to bed..
Felix Kling
+1  A: 

You can change your code to be more generic like this:

$(function() {
    $(".clickSave").hide();
    $(".choose-theme-bar ul li a").click(function() {
      $(this).find(".clickSave").toggle() //toggle current
       .end().parent().siblings().find(".clickSave").hide(); //hide others
    });
});

You can view an updated version of your demo here

Nick Craver
Thanks so much!
adamwstl
Quick question: When I remove the DIV from inside the <a> tags, it stops working? Can you tell me how to remedy this? Thanks!
adamwstl
@adamwstl: It stops working because then you have no element with class `clickSave` anymore. Hence, jQuery cannot select one.
Felix Kling
@adamwstl - Can you post the new markup? If it's *beside* the anchor, just change `$(this).find(".clickSave")` to `$(this).siblings(".clickSave")`, or change the click handler to the `<li>` by removing the "` a`" at the end of the selector.
Nick Craver
Thank you so much again Nick (and thanks Felix)
adamwstl
+1  A: 

This should work:

 $('.clickSave').click( function() {
    $('.clickSave').hide()
    $(this).show()
 })
Rishav Rastogi
Generally speaking `$(this).show()` shouldn't ever appear *directly* in the body of a `click` handler...what did you click on if it wasn't there already? ;) Also, semi-colons, **always**!
Nick Craver