1

I have a weird case that I need help.

I am trying to hide and show certain stuff when user clicks a button.

My html

 <div class='slide-content'> <h1>Title</h1> <div class='title-bar'> sub title here <div class='edit-container'> <a class='edit' href='#'>Edit</a> </div> </div> <div id='content' class='details'> <div class='contents'> <p>contents here</p> </div> <div class='break'></div> </div> <div id='edit-content' class='content-details'> <div class='contents'> <div class='editable-content'> contents here…... </div> </div> <div class='break'></div> </div> </div> <div class='slide-content'> …... 

another 10 slide-contents divs…

jquery

 $('.edit').on('click', function(e){ e.stopPropagation(); if($(this).text()=='Edit'){ $(this).text('Done'); $(this).closest('.slide-content').find($('.content-details')).show(); $(this).closest('.slide-content').find($('.details')).hide(); }else{ $(this).text('Edit'); $(this).closest('.slide-content').find($('.content-details')).hide(); $(this).closest('.slide-content').find($('.details').show()); } }) }); 

css

.content-details{ display:none; } 

My problem is, when I click the edit button first time, it shows my .content-details and hide .detail div. However, when I click the edit button again, it show every .details div in my page (even it's under different .slide-content div). My intension is to show only 1 .detail div under current .slide-content.

I am not sure what happen here. Can anyone help me out on this? Thanks a lot!

2 Answers 2

4

You aren't closing your parentheses properly:

$(this).closest('.slide-content').find($('.details').show()); 

To see the problem more clearly:

$(this).closest('.slide-content').find( $('.details').show() ); 

so you are explicitly calling $('.details').show().

You want this:

$(this).closest('.slide-content').find($('.details')).show(); 

But actually, you don't need a jquery object for find(), so this works just as well (here, and the other places you are using this pattern):

$(this).closest('.slide-content').find('.details').show(); 

Also, as a final note, I think it would be good to simplify your code and use a little caching:

$('.edit').on('click', function (e) { e.stopPropagation(); var $this = $(this); $this.text($this.text() == 'Edit' ? 'Done' : 'Edit'); $this.closest('.slide-content').find('.content-details, .details').toggle(); }); 
Sign up to request clarification or add additional context in comments.

Comments

1

Actually this is all you need: http://jsbin.com/IsUQaJA/1/edit

$('.edit').on('click', function(e){ e.preventDefault(); var txt = $(this).text(); $(this).text(txt=='Edit'?'Done':'Edit').closest('.slide-content') .find('.details, .content-details').toggle(); }); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.