Question

Fixed thanks to helpers below, see it in action here: http://bit.ly/15npgSC

I am learning jQuery and have come across a problem which I cannot find a fix for. I have a content slider which when a button is clicked, it slides open, and when the button is clicked again, it closes. This is all fine, the problem I have is that the slider opens automatically when the page loads, not only when clicked. How can I keep it closed when the page loads and have it only open when clicked? It works fine afterwards, its just that as the page loads, it opens. I tried putting $(document).click(function() { at the start which kind of worked but then when clicked it would open and then close immediately after opening with no click. I changed back to the jQuery code below but now have the problem of it opening when the page loads again.

$(document).ready(function() {
   $('.pull-me').click(function() {
       $('.panel').slideToggle('slow');
   });
   $('a').toggle(function() {
       $(this).html("Click to close!");},
       function() { $(this).html("Click to open!");
   }).click();
});

If you are able to fix this problem, could you explain why this occurs with my current code and why the fix stops that happening please? Thanks, Rafa.

Sorry for not posting the HTML code before, but this is it:

<div class="panel">
<br />
<br />
   <p>Now you see me!</p>
</div>
<div>
    <p class="slide"><a href="#" class="pull-me">Click to open!</a></p>
</div>
Was it helpful?

Solution

Because you did not post any HTML so I guess '.pull-me' is an 'a' element.

Pls try below code(remove .click()):

$(document).ready(function() {
   $('.pull-me').click(function() {
       $('.panel').slideToggle('slow');
   });

   $('a').toggle(function() {
       $(this).html("Click to close!");},
       function() { $(this).html("Click to open!");
   }); // modified here
});

You are triggering click event when the page first load.

OTHER TIPS

Try this:

// HTML

<div class="pull-me">
    Click here!
    </div>

<div class="panel">
    show/hide
</div>

// jQuery

$(document).ready(function() {
   $('.pull-me').click(function() {
       $('.panel').slideToggle('slow');
   });
       $('a').toggle(function() {
       $(this).html("Click to open!");},
       function() { $(this).html("Click to close!");
   });
});

check here in this JsFiddle -> http://jsfiddle.net/GXCuz/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top