views:

41

answers:

2

It seems that this code:

$(function(){
    $('.show_hide_login').toggle(
    function (){
            alert('show');
            $("div#fullpage").show();
            $("div#loginbox").show();
        },
  function (){
            alert('hide');
            $("div#loginbox").hide();
            $("div#fullpage").hide();
        }
  ); });

Any idea on why it would be running twice when I click on either link (two, one is a div and one is an anchor)?

+1  A: 

How many elements do you have with the .show_hide_login class? I'll guess you have two of those. In which case, $('.show_hide_login') result contains two elements, and toggle() is executed for each of them.

Franci Penov
I have a standard link: <a id="nav_login_register" class="show_hide_login" href="#">Login / Register</a>
Nathan
and also a fullpage div overlay which is set to display:none. <div id="fullpage" class="show_hide_login"></div>
Nathan
`.toggle()` with function parameters is just a click event. Unless the `.show_hide_login` elements are nested, it would only execute for the one that was clicked. :o)
patrick dw
Thanks, I've moved them out into separate .click events which works fine.. I guess that'll teach me for trying to cut corners :(
Nathan
@Nathan - It looks to me like you're using `.toggle()` correctly. Here's an example: http://jsfiddle.net/ZrMXN/
patrick dw
A: 

This isn't an answer to your question, but you could clean up your code a bit like so:

$(function() {
    $('.show_hide_login').toggle(
    function() {
        alert('show');
        $("#loginbox,#fullpage").show();
    }, function() {
        alert('hide');
        $("#loginbox,#fullpage").hide();
    });
});

As to your actual problem, I suspect Nick's guessed the culprit. Check out this demo to see the result of binding the same event twice: http://jsfiddle.net/9jPLv/

In addition to adding an alert prior to the binding of the toggle event, you could add in an unbind() and see if that solves the problem, like so:

$('.show_hide_login').unbind().toggle(

If that solves it, the toggle binding is definitely being run twice, so you'd just have to figure out why.

Ender