0

When you click on the button "test", Ajax takes the code in the file "second.html" and updates the content in the main page "main.html". When you click on the button "test__second", the script returns the content to the main page, but when you repeat the action, this button will not work, i.e its request only works once, but I want it to always work. Any suggestions?

Here is main.html:

<div class="container">
    <div class="test">Click</div>
    <div class="center">This is the main page</div>
</div>

And here is second.html from where the ajax takes the content:

<div class="test__second">Click</div>
<div class="center__second">This is second page</div>
<script>
$(document).ready(() => {
    $.ajax({
        async: false,
        type: 'GET',
        url: './setts.js',
        data: null,
        dataType: 'script'
    });
});
</script>

JavaScript file (setts.js):

$(document).ready(() => {
$('.test').click(() => {
    $.ajax({
        async: false,
        url: './second.html',
        cache: false,
        dataType: 'html',
        success: function(html) {
            $('.container').html(html);
        }
    });
});

$('.test__second').click(() => {
    $.ajax({
        async: false,
        url: './index.html',
        cache: false,
        dataType: 'html',
        success: function(html) {
            $('.container').html(html);
        }
    });
});
});
  • 2
    Does this answer your question? [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Robin Zigmond Jun 18 '20 at 16:23
  • `$(selector).click(` only applies to elements that exist at the time the code runs - you need to use event delegation (see link). – freedomn-m Jun 18 '20 at 16:24
  • 1
    Since you didn't include your HTML I can only guess. But my guess is that `.test__second` does not exist when the click handler is registered. You can either register the handler after the element exists, or look into [delegated events](https://api.jquery.com/on/). – Sam Axe Jun 18 '20 at 16:24
  • Actually yes and i find the problem – Knoddleboy Jun 18 '20 at 16:29
  • I had to do $(document).on('click', '.test__second', () => instead of $('.test__second').click(() => – Knoddleboy Jun 18 '20 at 16:30
  • yep, that's event delegation - see link above by @RobinZigmond for more details. – freedomn-m Jun 18 '20 at 16:43

0 Answers0