3

I have:

<button id="1"> Button 1 </button>
<span id="s1"> Span 1 </span>

<button id="2"> Button 2 </button>
<span id="s2"> Span 2 </span>

<button id="3"> Button 3 </button>
<span id="s3"> Span 3 </span>

What I need is:

-When click button 1, span 1 shows and when click again it disappears and shows the button 1. -When click button 2, span 2 shows and when click again it disappears and shows the button 2. -When click button 3, span 3 shows and when click again it disappears and shows the button 3.

I currently have a loop creating the html, assigning ids in an array and set to a class (.off) with display: none by default. For example:

$.(body).append( '<button id="'+[i]+'">Button'+[i]+'</button>
                  <span id="'+[i]+'" class="off">'

But I am having trouble selecting one by one. I get errors like, either only the first element works, or I click on 1 button and shows all the spans at the same time. My code:

for ( var j = 0; j < id.length; j++ ){
    $('button' ).on("click", function(e) {
        $('span' ).removeClass('off').addClass('on');
        $(this).on("click", function(e) {
             $('span').removeClass('on').addClass('off');             
         });
    });
});
1
  • 1
    +1 for good format of question. Commented Oct 17, 2013 at 7:39

1 Answer 1

4

There is not need to use a loop

$(document).on("click", 'button', function(e) {
    $(this).next('span' ).toggleClass('off on');
});

Demo: Fiddle

Sign up to request clarification or add additional context in comments.

5 Comments

Hey, yesterday it worked but today I added fresh Json with same format but new data and it broke toggleClass strangely. Add or RemoveClass still work but toggleClass broke. Any ideas?
@rebHelium whether your generated html has changed?
Not at all. Is very strange. I did console.log after every single variable and all the elements are the same compared side by side with both JSONs. One thing I notice is that when I use toggleClass() and press the button, in the developers tool it shows how it attempts to target the class but it does not succeed in re-writing it. Strange. I can use add / remove class and it works but then I am not succeeding in hiding the span again when I click the button for the second time.
@rebHelium are you sure the click handler is getting called... also it might be that some other script is interfering with this script... can you add a console.log() stmt in the handler function and see what is happening
Hi Arun. Thank you. Will do tomorrow morning and let you know.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.