Question

I am completely lost here, I have no idea as to why this is happening.

I have the following code in a .js file:

$( document ).ready(function() {
    showMessage();
    $( '#message' ).slideDown( 'fast' );

    //Hide Message//
    $( '#m_close' ).click(function( event ) {
        $( '#message' ).slideUp( 'fast' );
    });
    //---//
    $( '#m_button' ).click(function( event ) {
    showMessage();
    $( '#message' ).slideDown( 'fast' );
    });
});

Now, the message div is created and slides down perfectly fine when the page first loads. When I press #m_close, the div slides up perfectly. However, if I press #m_button, the message slides down with all the right info, but pressing #m_close does absolutely nothing. I get no errors in the dev console, nothing seems to go wrong, it just refuses to work. I added a slideDown to the #m_close so that it would close then reopen, and it does that, and the #m_close will work infinitely, until #m_button is pressed.

What is going on?

EDIT: my HTML per request:

<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <link href="includes/style.1.css" rel="stylesheet" type="text/css" />
    <script src="includes/jquery.js"></script>
</head>
<body>
    <div id="message">

    </div>
    <button id="m_button">Message</button>
    <script src="includes/functions.js"></script>
</body>

Was it helpful?

Solution

Looks like the message is loaded dynamically and the m_close might be added to the message element using showMessage() method.

so try

$( document ).ready(function() {
    showMessage();
    $( '#message' ).slideDown( 'fast' );

    //Hide Message//
    $( '#message' ).on('click', '#m_close', function( event ) {
        $( '#message' ).slideUp( 'fast' );
    });
    //---//
    $( '#m_button' ).click(function( event ) {
        showMessage();
        $( '#message' ).slideDown( 'fast' );
    });
});

when you use click to register a click event handler, it register the handler to only those elements that exists in the dom at that moment. when you call showMessage again teh existing m_close is removed and a new one is created so the click handler is no more attached to the new element. The solution here is to use event delegation as shown above

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top