0

i'm trying to learn some jQuery and i need some help on this little program, like you see i have a header which contains some text and i need to make sure that it expands to it's HTML content once been clicked using Toggle().

This my HTML

<body>
    <div class="tog">
        <h1 id="hh">
            <span> Click me to see my HTML content <span>
          <!-- A comment -->
        </h1>
    </div>
</body>

Here is my jQuery code

<script src="jquery.js"></script>
<script>

    $(function ()
    {
        $(".tog").click(function (){
        $('#hh').slideToggle("slow");

        $(this).toggleClass("active");

        if ($(this).text() == "Click me to see my HTML content ")
            $(this).html(h1);
        else
            $(this).text("Click me to see my HTML content ");
        });

</script>
P. Frank
  • 5,691
  • 6
  • 22
  • 50
hehexd123
  • 3
  • 1
  • 5
  • "expands to it's HTML content" ?? can you explain more what you are trying to achieve, as of now if i click the header, its getting replaced by the same text. – Nikhil Nanjappa Oct 25 '16 at 15:32
  • 1
    It's not exactly clear what you want to achieve. Do you want some more content to appear beneath the heading when we click the heading text? and disappear when we click heading again? – Mohit Bhardwaj Oct 25 '16 at 15:34
  • @NikhilNanjappa An empty HTML page with only a Text, when i click that text it change to show me it's HTML content with tags etc using Toggle() event. – hehexd123 Oct 25 '16 at 15:36
  • Instead of all that code, you can just make use of `$('#hh').toggleClass("hide");` – Nikhil Nanjappa Oct 25 '16 at 15:36

1 Answers1

0

The line $(this).html(h1); is not valid in your case, it will look for a variable named h1 not create a <h1> tag, the html() function takes only a string as an input so change your function to

$(".tog").click(function (){
  // you don't need any of the previous lines

  console.log($('#hh').html()); //this would show the comments as well

  if ($(this).text() == "Click me to see my HTML content ")
    $(this).html("<h1 id='hh'><span> Click me to see my HTML content <span><!-- A comment --></h1>");
  else
    $(this).text("Click me to see my HTML content ");
});

Check here

Nikhil Nanjappa
  • 6,454
  • 3
  • 28
  • 44
  • Hello sir, thank you for answering Your answer is correct but this Toggle shows how the HTML design looks in the page, is there anyway if i click it shows me the tags and what is inside like the comment and the span tag etc once i click – hehexd123 Oct 25 '16 at 15:56
  • Yes a simple `$('#hh').html();` would show you all the html contents including the comments inside it as well. Updated the answer & codepen – Nikhil Nanjappa Oct 25 '16 at 16:10
  • Ohh i see, thank you so much for your help! – hehexd123 Oct 25 '16 at 16:19