0
$(function() {
$('#toggle3').click(function () {
    $('.toggle').hide('1000');
    $('.toggle').text('I would like to add a navigation menu here'); // <--
$('.toggle').slideToggle('1000');

return false; 
    });
});

I am wondering the best way to edit the above code snippet to be able to hold HTML / CSS as I plan on calling a custom menu within. I will be using this snippet multiple times and calling multiple menus to trigger with toggle.

2
  • Well you would use html, not text Commented Nov 8, 2013 at 23:37
  • Thanks! But hey; using simple html does work; but does that make most sense with adding a content menu? Like that amount of code?! Commented Nov 8, 2013 at 23:46

1 Answer 1

1

If at all possible, try to avoid embedding html on javascript: you're likely to run into escaping issues and multiline strings, and the overall result usually isn't pretty.

You might want to store the HTML on the DOM itself:

<div>
  <span class="toggle" data-toggle="foo">Toggle foo</span>
  <span class="toggle" data-toggle="bar">Toggle bar</span>
</div>

<div id="navmenu-store">
  <div class='navmenu' data-for-toggle="foo">
    navmenu "foo"
  </div>

  <div class='navmenu' data-for-toggle="bar">
    navmenu "bar"
  </div>
</div>

On the CSS, hide the 'store':

#navmenu-store {
  display: none;
}

And then, with javascript, add the navmenus when requested:

$(".toggle").each(function() {
  var $toggle = $(this);
  var toggleName = $toggle.data("toggle");  
  var $navmenu = $(".navmenu[data-for-toggle=" + toggleName + "]");

  // Store the navmenu on the toggle for later access
  $navmenu.remove();
  $toggle.data("navmenu", $navmenu);
});

$(".toggle").on("click", function() {
  var $toggle = $(this);
  var $navmenu = $toggle.data("navmenu");

  var isInTheDom = $.contains(document, $navmenu[0]);

  if(isInTheDom) {
    $navmenu.remove();
  } else {
    // Here I'm inserting the navmenu after the toggle;
    // you can do whatever you want
    $navmenu.insertAfter($toggle);
  }
});

I've created a very simple jsbin as a proof of concept: http://jsbin.com/OwUWAlu/1/edit

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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.