user3544484
user3544484

Reputation: 851

jquery click toggle function

I am using the below to open and close a menu onclick - but most importantly, to change the link text from 'Menu' to 'Close'.

Is there a way to change the 'Close' link text back to 'Menu' with out clicking the link, but by clicking any where on the page?

<span class="menu-link">Menu</span>
<span class="menu-link" style="display:none">Close</span>

    <script type="text/javascript">
       jQuery(function() {
        jQuery(".menu-link").click(function()
         {                     
          jQuery(".menu-link").toggle();
          });
       });
    </script>

Thanks

Upvotes: 0

Views: 7811

Answers (2)

swestfall
swestfall

Reputation: 411

Add a click event to the body tag so that when you click elsewhere on the page, it will toggle it or you could have it only work to change it back to menu.

jQuery("body").click(function () {
        jQuery(".menu-link").toggle();
    });

Upvotes: 2

Jai
Jai

Reputation: 74738

Replace this:

jQuery(".menu-link").toggle();

with this:

$.trim($(this).text()) == "Menu" ? $(this).text("Close") : $(this).text("Menu");

And for this you don't need to have two spans, also use $.trim() to remove any leading/trailing whitespaces.

Demo

Upvotes: 1

Related Questions