Milkncookiez
Milkncookiez

Reputation: 7407

Change the content of div using jQuery

Parent div + 3 divs inside it. There's a link in one of the child divs, on click it changes the content of the parent and shows another link in the new content, that is supposed to change the content of the parent back to the original. The "going back" thingy doesn't work.

HTML:

<div id="parent">
    <div class="onCenterSmall">
    <a id="valueForMoney" href="javascript:: void(0)">Read more</a>
    </div>
    <div class="onCenterSmall">
    </div>
    <div class="onCenterSmall">
    </div>
</div>

JS:

$(document).ready(function () {
            $("#valueForMoney").click(function (e) {
                e.preventDefault();
                $("#mediaWindow").html('<div class="onCenterBig"><div id="backy"><a id="backLink" href="javascript:: void(0)">Go back</a></div></div><div class="onCenterSmall"></div>');
            });
        });

        $(document).ready(function () {
            $("#backLink").click(function (e) {
                e.preventDefault();
                $("#mediaWindow").html('<div class="onCenterSmall"></div><div class="onCenterSmall"></div><div class="onCenterSmall"></div>');
            });
        });

Upvotes: 0

Views: 147

Answers (2)

Rory McCrossan
Rory McCrossan

Reputation: 337714

The problem is because events are bound on load. As you are dynamically appending/removing elements after this, you need to delegate the events to elements which are always available through the page life cycle. Try this:

$(document).ready(function () {
    $("#mediaWindow").on('click', '#valueForMoney', function (e) {
        e.preventDefault();
        $("#mediaWindow").html('<div class="onCenterBig"><div id="backy"><a id="backLink" href="javascript:: void(0)">Go back</a></div></div><div class="onCenterSmall"></div>');
    });

    $("#mediaWindow").on('click', '#backLink', function (e) {
        e.preventDefault();
        $("#mediaWindow").html('<div class="onCenterSmall"></div><div class="onCenterSmall"></div><div class="onCenterSmall"></div>');
    });
});

Upvotes: 1

adeneo
adeneo

Reputation: 318342

The element is dynamically added, so you'll need a delegated event handler :

$(document).ready(function () {
    $('#mediaWindow').on('click', '#valueForMoney', function (e) {
        e.preventDefault();
        $("#mediaWindow").html('<div class="onCenterBig"><div id="backy"><a id="backLink" href="javascript:: void(0)">Go back</a></div></div><div class="onCenterSmall"></div>');
    });

    $('#mediaWindow').on('click', '#backLink', function (e) {
        e.preventDefault();
        $("#mediaWindow").html('<div class="onCenterSmall"></div><div class="onCenterSmall"></div><div class="onCenterSmall"></div>');
    });
});

Upvotes: 1

Related Questions