Pascal Hurni
Pascal Hurni

Reputation: 37

jquery .hide() and .show()

        $(".navItemWetten").click(function(){
            $(".navUnderItemWetten").hide();
        });

     <nav>
        <?php
            //Falls man eingeloggt ist
            if(isset($_SESSION['email'])){
        ?>
            <a href="logout.php" ><button class="logOutBtn" type="button">Log Out</button></a>
            <h1><p>Backend</p></h1><br /> <br />
            <a><li class="navItemWetten" >Wetten</li></a>
            <a><li class="navUnderItemWetten" >Super League</li></a>
        <?php
            } else {
        ?>
            <h1><p>Backend</p></h1>
        <?php
            }
        ?>
    </nav>

I just want, that when i click on the class navItemWetten that the class navUnderItemWetten is hidden. I have included ajax

Upvotes: 0

Views: 42

Answers (1)

Praveen Kumar Purushothaman
Praveen Kumar Purushothaman

Reputation: 167192

If I understand correctly, this doesn't work on items that load via AJAX. You need to use delegation. To elaborate, elements that are generated or recreated by an ajax call will lose any events that are attached to them, unless they are delegated:

$("body").on("click", ".navItemWetten", function(){
    $(".navUnderItemWetten").hide();
});

And remove the button that is inside of <a>. Also please do not nest <p> inside of <hX> tags.

Solution

  1. The whole layout is wrong. The LI can be contained only inside <ul> and you should not put any block level elemenets inside <a> tag.
  2. You must include the code inside document ready function.
  3. You must use .toggle() instead of .hide() and .show().

Snippet

// You must include the code inside document ready function.
$(function () {
    $(".navItemWetten").click(function(){
        $(".navUnderItemWetten").toggle();
    });
});
<!-- The whole layout is wrong. The LI can be contained only inside <ul> and you should not put any block level elemenets inside <a> tag. -->
<nav>
    <ul>
        <li class="navItemWetten" ><a>Wetten</a></li>
        <li class="navUnderItemWetten" ><a>Super League</a></li>
    </ul>
</nav> 

Upvotes: 2

Related Questions